Javascript - execute multiple different window.onscroll

僤鯓⒐⒋嵵緔 提交于 2019-12-08 23:33:50

问题


I am facing a little problem here. I have basic knowledge about Javascript and i want to do the following:

Right now, when you scroll down, the menu will get smaller. when you go back up, it will return to normal. I call this event with window.onscroll:

var diff = 0;
function effects(){
var topDistance = (document.documentElement &&     document.documentElement.scrollTop) ||  document.body.scrollTop;
var clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

if(topDistance > diff){ 
    diff = topDistance;
    if(clientWidth > 1024){
        if(topDistance > 300){
            document.getElementById("header").style.marginTop= "-100px";
        }
    }
}else if(topDistance < diff){
    diff = topDistance;
    if(clientWidth > 1024){
        if(topDistance > 300){
            document.getElementById("header").style.marginTop= "0";
        }
    }
}
}

window.onscroll = effects();

Now i want another function to have some effects to my call to action buttons, lets call the function "test", but if i want to do this the same way like above, the effects functions does not work anymore:

function test(){
//do something
}
window.onscroll = test();

Any help is welcome! I tihnk it won't be a big challenge to do this, but i am doing it wrong i guess. (PS: NO JQUERY PLEASE)


回答1:


You override onscroll function by doing window.onscroll = blabla

You can do :

window.onscroll = function() {
  effects();
  test();
}

or

window.addEventListener('scroll', effects);
window.addEventListener('scroll', test);



回答2:


You can use multiple listener for the scroll event.

window.addEventListener('scroll', effects);
window.addEventListener('scroll', test);

That way you don't override window.onscroll



来源:https://stackoverflow.com/questions/39998667/javascript-execute-multiple-different-window-onscroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!