javascript之通用的事宜侦听器函数

var EventUtil = {
    addEvent: function(element, type, handler) {
        if(element.addEventListener) { //DOM2级
            element.addEventListener(type, handler, false);
        }else if(element.attachEvent) {  //IE
            element.attachEvent("on"+ type, handler);
        }else {
            element["on" + type] = handler;
        }
    },
    removeEvent: function(element, type, handler) {
        if(element.removeEventListener) { //DOM2级
            element.removeEventListener(type, handler, false);
        }else if(element.detachEvent) {  //IE
            element.detachEvent("on"+ type, handler);
        }else {
            element["on" + type] = null;
        }
    },
    stopPropagation: function(ev) {
        if(ev.stopPropagation) {
            ev.stopPropagation();
        }else {
            ev.cancelBubble = true;
        }
    },
    preventDefault: function(ev) {
        if(ev.preventDefault) {
            ev.preventDefaule();
        }else {
            ev.returnValue = false;
        }
    },
    getTarget: function(ev) {
        return event.target || event.srcElement;
    },
    getEvent: function(e) {
        var ev = e || window.event;
        if(!ev) {
            var c = this.getEvent.caller;
            while(c) {
                ev = c.arguments[0];
                if(ev && Event == ev.constructor) {
                    break;
                }
                c = c.caller;
            }
        }
        return ev;
    }
};
            
    原文作者:bottle_
    原文地址: https://segmentfault.com/a/1190000007107028
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞