<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box{ 100px;height:100px; background: red } </style> </head> <body> <div class="box"></div> </body> <script> var obox = document.querySelector(".box"); // 赋值式绑定(DOM0级事件绑定) obox.onclick = function(){ console.log(1) } obox.onclick = function(){ console.log(2) // } // 删除赋值式事件绑定 obox.onclick = null; // 常用,没有兼容,简单 // 监听式绑定(DOM2级事件绑定) obox.addEventListener("click",fn1) function fn1(){ console.log(1) //1 } obox.addEventListener("click",function(){ console.log(2) //2 }) // 通过事件句柄找到原来的事件处理函数,删除 obox.removeEventListener("click",fn1) //2 // 兼容IE obox.attachEvent("onclick",fn1) function fn1(){ console.log(1) } obox.attachEvent("onclick",function(){ console.log(2) }) obox.detachEvent("onclick",fn1) console.log(obox.attachEvent)
封装函数 function removeEvent(ele,type,cb){ if(ele.removeEventListener){ ele.removeEventListener(type,cb) }else if(ele.detachEvent){ ele.detachEvent("on"+type,cb) }else{ ele["on"+type] = null; } } function addEvent(ele,type,cb){ if(ele.addEventListener){ ele.addEventListener(type,cb) }else if(ele.attachEvent){ ele.attachEvent("on"+type,cb) }else{ ele["on"+type] = cb; } }
调用函数
addEvent(obox,"click",fn1)
function fn1(){
console.log(1) //1
}
addEvent(obox,"click",fn2)
function fn2(){
console.log(2) //2
}
removeEvent(obox,"click",fn1)
removeEvent(obox,"click",fn2)
</script> </html>
demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box{ 100px;height:100px; background: red; position: absolute;left:0;top:0; } </style> </head> <body> <div class="box"></div> </body> <script> var obox = document.querySelector(".box"); var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var w = obox.offsetWidth; var h = obox.offsetHeight; // 行为过程:按下之后,移动,再抬起 obox.addEventListener("mousedown",function(eve){ // 获取按下的坐标,在按下的事件对象身上 var e1 = eve || window.event; // 为了防止移动过快,鼠标在某一瞬间离开元素,移动事件加给页面 document.addEventListener("mousemove",move) // 因为移动事件在抬起的时候,被删除,所以提前起名 function move(eve){ var e = eve || window.event; // 计算元素要移动的真正的距离:为鼠标相对于页面的坐标减去按下时相对于元素的坐标 var l = e.pageX - e1.offsetX; var t = e.pageY - e1.offsetY; // 边界限定 if(t < 0){ t = 0 } if(l < 0){ l = 0 } if(l > clientW - w){ l = clientW - w; } if(t > clientH - h){ t = clientH - h; } // 设置位置 obox.style.left = l + "px" obox.style.top = t + "px" } // 抬起时,删除移动,删除抬起 document.addEventListener("mouseup",up) function up(){ document.removeEventListener("mousemove",move) document.removeEventListener("mouseup",up) } }) </script> </html>