以下两短代码都表示一个简单功能,描述为:我想要的效果是,鼠标按下后,在页面移动不断计数,鼠标抬起则移除事件。但是下面的代码都有问题。
第一段代码的问题,找不到removeEventListener属性:
function counter (obj){
this.obj = obj;
this.num = 0;
}
counter.prototype.start = function(){
var self = this;
self.obj.addEventListener( "mousemove" , self.move , false );
self.obj.addEventListener( "mouseup" , self.end , false );
}
counter.prototype.move = function(){
var self = this;
document.title = self.num++;
}
counter.prototype.end = function(){
var self = this;
self.obj.removeEventListener( "mousemove" , self.move , false );
self.obj.removeEventListener( "mouseup" , self.end , false );
}
counter.prototype.init = function(){
var self = this;
self.obj.addEventListener( "mousedown" , self.start , false );
}
var counterNew = new counter(document);
counterNew.init();
以上代码在init中有修改,原来是 self.end,搞错了,应该是 self.start
第二段代码的问题,可能是因为绑定和删除都是匿名函数,所以无法移除事件:
function counter (obj){
this.obj = obj;
this.num = 0;
}
counter.prototype.start = function(){
var self = this;
self.obj.addEventListener( "mousemove" , function(){
self.move();
} , false );
self.obj.addEventListener( "mouseup" , function(){
self.end();
} , false );
}
counter.prototype.move = function(){
var self = this;
document.title = self.num++;
}
counter.prototype.end = function(){
var self = this;
self.obj.removeEventListener( "mousemove" , function(){
self.move();
} , false );
self.obj.removeEventListener( "mouseup" , function(){
self.end();
} , false );
}
counter.prototype.init = function(){
var self = this;
self.obj.addEventListener( "mousedown" , function(){
self.start();
} , false );
}
var counterNew = new counter(document);
counterNew.init();
请问大家,有解决方案吗?多谢了
非面向对象实现
面向对象实现
第二种也可以通过
call
或者apply
实现,TZ可以试试