addEventListener解决多个window.onscroll共存的2个方法

时间:2021-11-12 04:38:02

方法1.(注意第一个和第二个的先后次序)

window.onscroll=function(){console.log('第一个');}
var oldMethod = window.onscroll;
if(typeof oldMethod == 'function'){
    window.onscroll = function(){
        oldMethod.call(this);
        console.log('第二个');
    }
}

方法2.(无须注意顺序

function addEvent(obj,type,fn){
    if(obj.attachEvent){ //ie
        obj.attachEvent('on'+type,function(){
            fn.call(obj);
        })
    }else{
        obj.addEventListener(type,fn,false);
    }
}
addEvent(window,'scroll',function(){console.log('第n个')});
addEvent(window,'scroll',function(){console.log('第n+1个')});