兼容IE8 addEventListener、removeEventListener 函数

//兼容bind函数
if(!Function.prototype.bind){
    Function.prototype.bind = function(){
        if(typeof this !== 'function'){
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }
        var _this = this;
        var obj = arguments[0];
        var ags = Array.prototype.slice.call(arguments,1);
        return function(){
            _this.apply(obj,ags);
        };
    };
}

//兼容addEventListener函数
function addEventListener(ele,event,fn){
    if(ele.addEventListener){
        ele.addEventListener(event,fn,false);
    }else{
        ele.attachEvent('on'+event,fn.bind(ele));
    }
}

//兼容removeEventListener函数
function removeEventListener(ele,event,fn){
    if(ele.removeEventListener){
        ele.removeEventListener(event,fn,false);
    }else{
        ele.detachEvent('on'+event,fn.bind(ele));
    }
}

猜你喜欢

转载自www.cnblogs.com/jpfss/p/9116381.html