自定义 绑定响应函数 解除响应函数 .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);
        }
    }
相关文章
相关标签/搜索