1 // 把所有方法封装到一个对象里面,充分考虑兼容写法 2 var EventUtil = { 3 // 添加DOM事件 4 addEvent: function(element, type, handler) { 5 if(element.addEventListener) { //DOM2级 6 element.addEventListener(type, handler, false); 7 }else if(element.attachEvent) { //IE 8 element.attachEvent("on"+ type, handler); 9 }else { 10 element["on" + type] = handler; 11 } 12 }, 13 // 移除DOM事件 14 removeEvent: function(element, type, handler) { 15 if(element.removeEventListener) { //DOM2级 16 element.removeEventListener(type, handler, false); 17 }else if(element.detachEvent) { //IE 18 element.detachEvent("on"+ type, handler); 19 }else { 20 element["on" + type] = null; 21 } 22 }, 23 // 阻止事件冒泡 24 stopPropagation: function(ev) { 25 if(ev.stopPropagation) { 26 ev.stopPropagation(); 27 }else { 28 ev.cancelBubble = true; 29 } 30 }, 31 // 阻止默认事件 32 preventDefault: function(ev) { 33 if(ev.preventDefault) { 34 ev.preventDefaule(); 35 }else { 36 ev.returnValue = false; 37 } 38 }, 39 // 获取事件源对象 40 getTarget: function(ev) { 41 return event.target || event.srcElement; 42 }, 43 // 获取事件对象 44 getEvent: function(e) { 45 var ev = e || window.event; 46 if(!ev) { 47 var c = this.getEvent.caller; 48 while(c) { 49 ev = c.arguments[0]; 50 if(ev && Event == ev.constructor) { 51 break; 52 } 53 c = c.caller; 54 } 55 } 56 return ev; 57 } 58 }; 59