自定義 綁定響應函數 解除響應函數 .addEventListener 兼容 .attachEvent

嗯哼。很少說,直接上代碼。瀏覽器

  • // 自定義 綁定響應函數    兼容性封裝 Test Already.
    function bindEventFunc(obj, eventStr, func){
        // console.log(!!obj.addEventListener == true);    // true
        // console.log(!!obj.attachEvent == true );    // false
        if(obj.addEventListener){
            // 大多數瀏覽器支持, IE8 及如下不支持
            obj.addEventListener(eventStr, func, false);    // false 指定在捕獲的階段的時候不觸發事件
        }else{
            // IE5 - IE10 支持
            obj.attachEvent("on"+eventStr, function(){
                func().call(obj);
            });
        }
    }

 

  • // 自定義 解除響應函數    兼容性封裝 Test Already.
    function removeEventFunc(obj, eventStr, func){
        // console.log(!!obj.removeEventListener == true);    // true
        // console.log(!!obj.detachEvent == true );    // false
        if(obj.removeEventListener){
            // 大多數瀏覽器支持, IE8 及如下不支持
            obj.removeEventListener(eventStr, func);
        }else if(obj.detachEvent){
            // IE5 - IE10 支持
            obj.detachEvent("on"+eventStr, func);
        }
    }
相關文章
相關標籤/搜索