1 var Event = { 2 //注册事件 3 addEvent: function(element,type,handler){ 4 if(element.addEventListener){ //DOM2级 5 element.addEventListener(type,handler,false); //false为冒泡,true为捕获 6 }else if(element.attachEvent){ //IE 7 element.attachEvent("on"+type,function(){ //默认皆为冒泡 8 handler.call(element); 9 }); 10 }else{ 11 element["on"+type] = handler; //DOM0级 12 } 13 }, 14 //取消事件 15 removeEvent: function(element,type,handler){ 16 if(element.removeEventListener){ 17 element.removeEventListener(type,handler,false); 18 }else if(element.detachEvent){ 19 element.detachEvent("on"+type,handler); 20 }else{ 21 element["on"+type] = null; 22 } 23 }, 24 //防止冒泡行为 25 stopPropagation: function(event){ 26 if(event.stopPropagation){ //非IE 27 event.stopPropagation(); 28 }else{ //IE 29 event.cancleBubble = true; 30 } 31 }, 32 //阻止默认行为 如<a>的默认链接行为 33 preventDefault: function(event){ 34 if(event.preventDefault){ // 35 event.preventDefault(); 36 }else{ //IE 37 event.returnValue = true; 38 } 39 }, 40 //获取事件对象 41 getEvent: function(event){ 42 return event || window.event; //FF通过传过来的参数event使用,IE通过window.event取用 43 }, 44 //获取触发事件的目标源 45 getTarget: function(event){ 46 return event.target || event.srcElement; //后者为了兼容IE 47 } 48 };