记录这个没别的意思,之前这段代码貌没有问题,但是调试的时候移除事件貌不能用源代码如下: !--拖动div--!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtdhtml xmlns=http://www.w3.
记录这个没别的意思,之前这段代码貌似没有问题,但是调试的时候移除事件貌似不能用源代码如下:
无标题文档 script>-->
一直搞不懂为什么事件不能移除?这个代码就一直放下了,结果刚才看《javascript高级程序设计》才知道removeEventListener不能传无参的构造函数,因为addEventListener可以给元素绑定多个事件,所以removeEventListener的时候找不到了!修改好的代码如下:
/** * 绑定事件 **/ var addEvent = function(obj, eventName, handle) { if(window.addEventListener) { obj.addEventListener(eventName, handle, false); }else { obj.attachEvent("on" + eventName, handle); } } var removeEvent = function (obj, eventName, handle){ if (window.removeEventListener) { obj.removeEventListener(eventName, handle, false); }else if(window.detachEvent){ obj.detachEvent("on" + eventName, handle); }else { obj["on"+eventName] = null; } }; var $ = function(id) { return "string" == typeof id ? document.getElementById(id) : id; } //js兼容性 var page = { event: function (evt) { var ev = evt || window.event; return ev; }, target: function(evt) { return evt.target || evt.srcElement; }, pageX: function (evt) { var e = this.event(evt); return e.pageX || (e.clientX + document.body.scrollLeft - document.body.clientLeft); }, pageY: function (evt) { var e = this.event(evt); return e.pageY || (e.clientY + document.body.scrollTop - document.body.clientTop); }, layerX: function (evt) { var e = this.event(evt); return e.layerX || e.offsetX; }, layerY: function (evt) { var e = this.event(evt); return e.layerY || e.offsetY; } } var drag = function(obj) { obj.style.position="absolute"; var mousedownFun, mousemoveFun, mouseupFun, x, y, target; mousedownFun = function(event){ target = page.target(event); x = page.layerX(event); y = page.layerY(event); addEvent(obj,"mousemove", mousemoveFun); addEvent(obj,"mouseup", mouseupFun); }; mousemoveFun = function(event){ var tx = page.pageX(event) - x; var ty = page.pageY(event) - y; target.style.left = tx + "px"; target.style.top = ty + "px"; }; mouseupFun = function(event) { removeEvent(obj, "mousemove",mousemoveFun); removeEvent(obj, "mouseup",mouseupFun); } addEvent(obj,"mousedown", mousedownFun); } drag($("div2"));
声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。TEL:177 7030 7066 E-MAIL:11247931@qq.com