简体   繁体   English

使JS EventListener持续运行

[英]Making JS EventListener run constantly

A couple of days ago someone here offered me a solution for a script that changes the color of a div when scrolling. 几天前,有人在这里为我提供了一种脚本解决方案,该脚本可在滚动时更改div的颜色。

This is the code I used: 这是我使用的代码:

    const x = document.getElementById("menuID");
window.addEventListener("scroll", () => {
    if(window.pageYOffset >= 105 && window.pageYOffset < 775){
        x.classList.add("color1");
    } else {
        x.classList.add("color2");
    }
});

It works, nevertheless I want it to keep functioning after the page loaded, so its able to change to ''color.2''. 它可以工作,但是我希望它在页面加载后继续运行,因此它可以更改为“ color.2”。 Is this possible? 这可能吗?

Add one more event listener on you document and run the same callback from there also : 在您的文档上再添加一个事件监听器,并从那里运行相同的回调:

const x = document.getElementById("menuID");
function callback(){
    if(window.pageYOffset >= 105 && window.pageYOffset < 775){
        x.classList.add("color1");
    } else {
        x.classList.add("color2");
    }
}

window.addEventListener("scroll",callback);
window.addEventListener("load",callback);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM