zoukankan      html  css  js  c++  java
  • js事件监听/鼠标滚轮/行为/冒泡/键盘的兼容性写法

    addEvent:function(el,type,fn,capture) {
        if (window.addEventListener) {    
            if (type === "mousewheel" && document.mozHidden !== undefined) {
                type = "DOMMouseScroll";
            }    
            el.addEventListener(type, fn, !!capture);
        } else if (window.attachEvent) {
            el.attachEvent("on" + type, fn);
        }
    },
    removeEvent:function(el,type,fn,capture) {
        if (window.removeEventListener) {    
            if (type === "mousewheel" && document.mozHidden !== undefined) {
                type = "DOMMouseScroll";
            }    
            el.removeEventListener(type, fn, !!capture);
        } else if (window.detachEvent) {
            el.detachEvent("on" + type, fn);
        }
    },
    //对鼠标滚轮、行为、冒泡以及键盘做的兼容性处理
    eventCompat:function(e) {
        e || (e = root.event);
        var type = e.type;
        if (type == 'DOMMouseScroll' || type == 'mousewheel') {
            e.delta = (e.wheelDelta) ? -e.wheelDelta / 120 : (e.detail || 0) / 3;
        }
        if (e.srcElement && !e.target) {
            e.target = e.srcElement;    
        }
        //阻止默认行为
        if (!e.preventDefault) {
            e.preventDefault = function() {
                e.returnValue = false;
            };
        }
        //阻止冒泡
        if (!e.stopPropagation && e.cancelBubble !== undefined) {
            e.stopPropagation = function() {
                e.cancelBubble = true;
            };
        }
        //键盘的兼容性处理
        if(e.which == null){
            e.which = e.charCode != null ? e.charCode : e.keyCode;
        }
        /* 
           ......其他一些兼容性处理 */
        return e;
    },
    bindAsEventListener:function(context, fun) {
        var self = this;
        return function(e) {
            return fun.call(context, self.eventCompat(e));
        }
    }
    
    
    //调用:
    var dom = document.getElementById('btn');
    var object = {
        clickCtrl:function(e){
            alert(e);    
        }
    };
    
    addEvent(dom, "click", function(){
        alert(dom.id);                                       
    });
    
    addEvent(dom, "mousedown", 
        bindAsEventListener(object, function(e){ 
            object.ClickCtrl(e);
    }));
     
  • 相关阅读:
    解决Windows 10每次重启默认浏览器都被重置为IE的一个办法
    使用cookie登录百度网盘账号
    【C++ Primer | 14】重载运算
    Visual Studio Code 快捷键的使用
    【C++ Primer | 8】IO库
    Git push常见用法
    Git 基础
    Git连接GitHub仓库详解
    ceph关于rpm包构建的教程
    monitor综合
  • 原文地址:https://www.cnblogs.com/gulan/p/5884940.html
Copyright © 2011-2022 走看看