20,事件应用,事件绑定attachEvent,addEventListener,捕获事件setCapture()
在同一个对象上加两次相同的事件,会被覆盖,所以用事件绑定,就不会被覆盖了;
事件绑定;obj.attachEvent('onclick',fun)://ie 解除绑定:detachEvent;
obj.addEventListener('click',fun,false)//firefox.chrome removeEventListener;
事件捕获:obj.setCapture();只在ie6-8中解决问题,ie9,ff,chrome中的拖拽影响其他对象的问题已经被return false解决掉;
例子:事件绑定
封装事件绑定函数function attachEvent(obj,attr,fun);
js
<script> function myAddEvent(obj, ev, fn) { if(obj.attachEvent) { obj.attachEvent('on'+ev, fn); } else { obj.addEventListener(ev, fn, false); } } window.onload=function () { var oBtn=document.getElementById('btn1'); myAddEvent(oBtn, 'click', function (){ alert('a'); }); myAddEvent(oBtn, 'click', function (){ alert('b'); }); }; </script>
例子:拖拽(当页面中不只是有一个div,还包括文字,图片等的时候,拖拽div,不影响其他对象)
用事件绑定,把其他对象的事件都绑定到div上,当鼠标抬起时再接触绑定:oDiv.releaseCapture();
<script> window.onload=function () { var oDiv=document.getElementById('div1'); var disX=0; var disY=0; oDiv.onmousedown=function (ev) { var oEvent=ev||event; disX=oEvent.clientX-oDiv.offsetLeft; disY=oEvent.clientY-oDiv.offsetTop; if(oDiv.setCapture) { //IE oDiv.onmousemove=mouseMove; oDiv.onmouseup=mouseUp; oDiv.setCapture(); } else { //Chrome、FF document.onmousemove=mouseMove; document.onmouseup=mouseUp; } function mouseMove(ev) { var oEvent=ev||event; var l=oEvent.clientX-disX; var t=oEvent.clientY-disY; oDiv.style.left=l+'px'; oDiv.style.top=t+'px'; } function mouseUp() { this.onmousemove=null; this.onmouseup=null; if(oDiv.releaseCapture) { oDiv.releaseCapture(); } } return false; //chrome、ff、IE9 }; }; </script>
例子:div2套div1,div1拖拽拖不出div2;
将拖拽改进,四边最大移动的距离设置成div2的四边;
<script> window.onload=function () { var oDiv=document.getElementById('div1'); var oDiv2=document.getElementById('div2'); var disX=0; var disY=0; oDiv.onmousedown=function (ev) { var oEvent=ev||event; disX=oEvent.clientX-oDiv.offsetLeft; disY=oEvent.clientY-oDiv.offsetTop; document.onmousemove=function (ev) { var oEvent=ev||event; var l=oEvent.clientX-disX; var t=oEvent.clientY-disY; if(l<0) { l=0; } else if(l>oDiv2.offsetWidth-oDiv.offsetWidth) { l=oDiv2.offsetWidth-oDiv.offsetWidth; } if(t<0) { t=0; } else if(t>oDiv2.offsetHeight-oDiv.offsetHeight) { t=oDiv2.offsetHeight-oDiv.offsetHeight; } oDiv.style.left=l+'px'; oDiv.style.top=t+'px'; }; document.onmouseup=function () { document.onmousemove=null; document.onmouseup=null; }; return false; }; }; </script>