天天看點

JavaScript --- > 跨浏覽器的事件對象

var EventUtil={
    
    addHandler: function(element, type, handler){  // 添加事件方法
        if (element.addEventListener){
            element.addEventListener(type, handler, false);  // 添加監聽事件,第3個參數false代表:冒泡階段
        } else if (element.attachEvent) {
            element.attachEvent("on" + type, handler);
        } else {
            element["on" + type] = handler;
        }
    },
    
    getEvent: function(event){  // 跨浏覽器擷取事件對象
        return event ? event : window.event;
    },
    
    getTarget: function(event){
        return event.target || event.srcElement;
    },
    
    preventDefault: function(event){
        if (event.preventDefault){
            event.preventDefault();
        } else {
            event.returnValue = false;
        }
    },
    
    removeHandler: function(element, type, handler) {   
        if (element.removeEventListener){
            element.removeEventListener(type, handler, false);
        } else if (element.detachEvent){
            element.detachEvent("on" + type, handler);
        } else { 
            element["on" + type] = null;
        }
    },
    
    stopPropagation: function(event){  
        if (event.stopPropagation){
            event.stopPropagation();
        } esle {
            event.cancelBubble = true;
        }
    }
};     
           

摘自《JavaScript進階程式設》(第3版) P360

繼續閱讀