首页 > 代码库 > 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事件监听的兼容写法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。