1 var EventUtil = { 2 3 //添加事件 4 addHandler: function(element, type, handler){ 5 if (element.addEventListener) { 6 element.addEventListener(type, handler, false); //冒泡阶段触发 7 } else if (element.attachEvent) { 8 element.attachEvent("on"+type, handler); 9 } else { 10 element["on"+type] = handler; 11 } 12 }, 13 //移除事件 14 removeHandler: function(element, type, handler){ 15 if (element.removeEventListener) { 16 element.removeEventListener(type, handler, false); //冒泡阶段触发 17 } else if (element.detachEvent) { 18 element.detachEvent("on"+type, handler); 19 } else { 20 element["on"+type] = null; 21 } 22 }, 23 24 //获取事件对象Event 25 getEvent: function(event){ 26 return event? event:window.event; 27 }, 28 //获取目标元素 29 getTarget: function(event){ 30 return event.target || event.srcElement; 31 }, 32 //阻止默认操作方式 33 preventDefault: function(event){ 34 if (event.preventDefault) { 35 event.preventDefault(); 36 } else { 37 event.returnValue = false; 38 } 39 }, 40 //停止冒泡事件 41 stopPropagation: function(event){ 42 if (event.stopPropagation) { 43 event.stopPropagation(); 44 } else { 45 event.cancelBubble = true; 46 } 47 } 48 49 };
测试代码:
1 $(document).ready(function(){ 2 var btn = document.getElementById("btn"); 3 btn.onclick = function(event){ 4 event = EventUtil.getEvent(event); 5 var target = EventUtil.getTarget(event); 6 alert(target); 7 EventUtil.stopPropagation(event); 8 } 9 document.body.onclick = function(event){ 10 alert("BODY"); 11 } 12 });