基本event封装:阻止冒泡、默认事件等
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <div id="box"> <input type="button" value="按钮3" id="btn3"> <a href="http://www.sogou.com/sie?hdq=AQxRG-7004&query=addEventListener%20of%20undefined&p=99350103&oq=&ri=-2" id="go">跳转</a> </div> <script type="text/javascript"> var btn3 = document.getElementById('btn3'); var box = document.getElementById('box'); var id = document.getElementById('id'); function showMes(event) { event = event || window.event; //在IE8之前要用的是window.event; var ele = event.target || event.srcElement; //在IE8之前用的不是target而是srcElement alert(ele.nodeName); event.stopPropagation(); } function showM() { alert("RGE"); } function stopGo(event) { event.stopPropagation(); event.preventDefault(); } var eventUtil = { //给元素添加事件 addHandler: function(element, type, handler) { if(element.addEventListener) { element.addEventListener(type,handler,false); } else if(element.attachEvent) { element.attachEvent('on'+type, handler); } else { element['on'+type] = handler; } }, //给元素删除事件 removeHandler: function(element, type, handler) { if(element.removeEventListener) { element.removeEventListener(type,handler,false); } else if(element.detachEvent) { element.detachEvent('on'+type, handler); } else { element['on'+type] = null; } }, //获得兼容浏览器的事件对象 getEvent: function(event) { return event?event:window.event; }, //获取事件类型 getType: function(event) { return event.type; }, //获取时间来自哪个元素 getElement: function(event) { return event.target || event.srcElement; }, //阻止取消事件的默认行为 preventDefault:function(event) { if(event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } }, //阻止时间冒泡 stopPropagation: function(event) { if(event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } } } eventUtil.addHandler(btn3, 'click', showMes); eventUtil.addHandler(box, 'click', showM); eventUtil.addHandler(go, 'click', stopGo); </script> </body> </html>
把每一个事件封装在对象里面,把每一个功能封装在方法里面