HTML事件处理:
<input onclick="fn()" type="button" value="按钮"/> <script> function fn(){ alert(1); } </script>
DEMO 0级事件处理:
<input id="btn" type="button" value="按钮"/> <script> var oBtn = document.getElementById('btn'); //添加事件 oBtn.onclick = function (){ alert(1); }; //移除事件 oBtn.onclick = null; </script>
DEMO 0级事件处理的缺陷,添加多个相同事件只能执行一个,因此有了DEMO2级事件处理;
DEMO2级事件处理:
//标准:addEventListener、removeEventListener //IE:attachEvent、detachEvent //兼容处理: //添加事件绑定 function addEvent(o, ev, fn){ if(o.addEventListener){ o.addEventListener(ev, fn, false); }else if(o.attachEvent){ o.attachEvent('on'+ev, function(){ fn.call(o); // IE兼容处理 }); }else{ o['on'+ev] = fn; } } //移除事件绑定 function removeEvent(o, ev, fn){ if(o.removeEventListener){ o.removeEventListener(ev, fn, false); }else if(o.detachEvent){ o.detachEvent('on'+ev, fn); }else{ o['on'+ev] = null; } }
IE+标准:事件冒泡(从内到外):
<div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> <script> //事件冒泡:当一个元素触发某事件时,同时会把事件传递给父级(从内到外) window.onload = function(){ var oDiv1 = document.getElementById('div1'); var oDiv2 = document.getElementById('div2'); var oDiv3 = document.getElementById('div3'); function fn(){ alert(this.id); }; oDiv1.onclick = fn; oDiv2.onclick = fn; oDiv3.onclick = fn; }; </script>
标准:事件捕获(从外到内):
<div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> <script> //事件捕获:当一个元素触发某事件时,同时会把事件传递给子级(从外到内) window.onload = function(){ var oDiv1 = document.getElementById('div1'); var oDiv2 = document.getElementById('div2'); var oDiv3 = document.getElementById('div3'); function fn(){ alert(this.id); }; //true:捕获, false:冒泡 oDiv1.addEventListener('click', fn, true); oDiv2.addEventListener('click', fn, true); oDiv3.addEventListener('click', fn, true); }; </script>
标准:事件冒泡+捕获(先捕获后冒泡):
<div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> <script> //先捕获后冒泡 window.onload = function(){ var oDiv1 = document.getElementById('div1'); var oDiv2 = document.getElementById('div2'); var oDiv3 = document.getElementById('div3'); //true:捕获, false:冒泡 oDiv1.addEventListener('click', function(){ alert(1); }, false); oDiv1.addEventListener('click', function(){ alert(2); }, true); oDiv3.addEventListener('click', function(){ alert(3); }, false); }; </script>
事件对象跨浏览器兼容:
//获取事件对象 function getEvent(event){ return event ? event : window.event; } //获取目标 function getTarget(event){ return event.target || event.srcElement; } //阻止冒泡 function stopPropagation(event){ if(event.stopPropagation){ //W3C event.stopPropagation(); }else{ //IE event.cancelBubble = true; } } //阻止默认行为 function preventDefault(event){ if(event.preventDefault){ //W3C event.preventDefault(); }else{ //IE event.returnValue = false; } }