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;
    }
};
            

你可能感兴趣的:(javascript,事件监听,事件代理)