首页 > 代码库 > js事件监听的兼容写法

js事件监听的兼容写法

 1 addEvent:function(el,type,fn,capture) { 2     if (window.addEventListener) {     3         if (type === "mousewheel" && document.mozHidden !== undefined) { 4             type = "DOMMouseScroll"; 5         }     6         el.addEventListener(type, fn, !!capture); 7     } else if (window.attachEvent) { 8         el.attachEvent("on" + type, fn); 9     }10 },11 removeEvent:function(el,type,fn,capture) {12     if (window.removeEventListener) {    13         if (type === "mousewheel" && document.mozHidden !== undefined) {14             type = "DOMMouseScroll";15         }    16         el.removeEventListener(type, fn, !!capture);17     } else if (window.detachEvent) {18         el.detachEvent("on" + type, fn);19     }20 },21 //对鼠标滚轮做的兼容性处理22 eventCompat:function(e) {23     e || (e = window.event);24     var type = e.type;25     if (type == ‘DOMMouseScroll‘ || type == ‘mousewheel‘) {26         e.delta = (e.wheelDelta) ? -e.wheelDelta / 120 : (e.detail || 0) / 3;27     }28     //alert(e.delta);29     if (e.srcElement && !e.target) {30         e.target = e.srcElement;    31     }32     if (!e.preventDefault) {33         e.preventDefault = function() {34             e.returnValue = http://www.mamicode.com/false;35         };36     }37     if (!e.stopPropagation && e.cancelBubble !== undefined) {38         e.stopPropagation = function() {39             e.cancelBubble = true;40         };41     }42     /* 43        ......其他一些兼容性处理 */44     return e;45 },46 bindAsEventListener:function(context, fun) {47     var self = this;48     return function(e) {49         return fun.call(context, self.eventCompat(e));50     }51 }52 53 54 //调用:55 var dom = document.getElementById(‘btn‘);56 var object = {57     clickCtrl:function(e){58         alert(e);    59     }60 };61 62 addEvent(dom, "click", function(){63     alert(dom.id);                                       64 });65 66 addEvent(dom, "mousedown", 67     bindAsEventListener(object, function(e){ 68         object.ClickCtrl(e);69 }));

 

js事件监听的兼容写法