以下兩短代碼都表示一個簡單功能,描述為:我想要的效果是,鼠標(biāo)按下后,在頁面移動不斷計數(shù),鼠標(biāo)抬起則移除事件。但是下面的代碼都有問題。第一段代碼的問題,找不到removeEventListener屬性:functioncounter(obj){this.obj=obj;this.num=0;}counter.prototype.start=function(){varself=this;self.obj.addEventListener("mousemove",self.move,false);self.obj.addEventListener("mouseup",self.end,false);}counter.prototype.move=function(){varself=this;document.title=self.num++;}counter.prototype.end=function(){varself=this;self.obj.removeEventListener("mousemove",self.move,false);self.obj.removeEventListener("mouseup",self.end,false);}counter.prototype.init=function(){varself=this;self.obj.addEventListener("mousedown",self.start,false);}varcounterNew=newcounter(document);counterNew.init();以上代碼在init中有修改,原來是self.end,搞錯了,應(yīng)該是self.start第二段代碼的問題,可能是因為綁定和刪除都是匿名函數(shù),所以無法移除事件:functioncounter(obj){this.obj=obj;this.num=0;}counter.prototype.start=function(){varself=this;self.obj.addEventListener("mousemove",function(){self.move();},false);self.obj.addEventListener("mouseup",function(){self.end();},false);}counter.prototype.move=function(){varself=this;document.title=self.num++;}counter.prototype.end=function(){varself=this;self.obj.removeEventListener("mousemove",function(){self.move();},false);self.obj.removeEventListener("mouseup",function(){self.end();},false);}counter.prototype.init=function(){varself=this;self.obj.addEventListener("mousedown",function(){self.start();},false);}varcounterNew=newcounter(document);counterNew.init();請問大家,有解決方案嗎?多謝了
為什么面向?qū)ο笾衋ddEventListener找不到屬性或者無法移除事件?
九州編程
2019-04-21 20:41:04