简体   繁体   English

让 JavaScript if 语句定期运行,而不是在不使用 setInterval 的情况下运行一次

[英]Having JavaScript if statement run periodically and not once without using setInterval

I'm currently running an if statement looped by setInterval 100ms to add and remove classes when the browser is scrolled more than 450px.我目前正在运行一个由 setInterval 100ms 循环的 if 语句,以在浏览器滚动超过 450 像素时添加和删除类。 Obviously, not looping it makes it only run once which is not what I want.显然,不循环它只会运行一次,这不是我想要的。 I've heard setInterval may lag the browser though, so is there a way to optimize this code better?我听说 setInterval 可能会滞后于浏览器,那么有没有办法更好地优化此代码?

setInterval(function() {
  if(window.scrollY > 450) {
    document.querySelector('.whatever').classList.remove("whatever2);
  } else {
    document.querySelector('.whatever').classList.add("whatever3");
  }
}, 100);

The code works in this manner, but obviously I want it as optimized as possible.代码以这种方式工作,但显然我希望它尽可能优化。 I used to use jQuery, and I was able to replicate this with document.ready as so:我曾经使用 jQuery,并且我能够使用 document.ready 复制它,如下所示:

$(document).ready(function(){
    $(window).scroll(checkScroll);
    function checkScroll() {
        if($(window).scrollTop()>=450) {
            $('.whatever').addClass('whatever2');
        }else{
            $('.whatever').removeClass('whatever3');
        }
    }
});

I struggle converting it to JavaScript in a better manner though.不过,我很难以更好的方式将其转换为 JavaScript。

Try:尝试:

 document.addEventListener('DOMContentLoaded', function() { window.addEventListener('scroll', checkScroll) function checkScroll() { if (window.scrollY >= 450) { document.querySelector('.whatever').classList.add('whatever2'); } else { document.querySelector('.whatever').classList.remove('whatever3'); } } })
 html, body{ height:200%; } .whatever{ position:fixed; top:0; left:0; } .whatever2{ background-color:red; } .whatever3{ background-color:blue; }
 <div class="whatever whatever3"> Hello World! </div>

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

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