js事件监听的兼容写法

Posted codeing or artist ?

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = 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事件监听的兼容写法的主要内容,如果未能解决你的问题,请参考以下文章

JS事件监听的添加方法

添加事件的兼容性写法

监听鼠标滚轮事件

JS原生 未来元素监听写法

js事件对象兼容性写法

js滚轮事件兼容写法