[英]Having JavaScript if statement run periodically and not once without using setInterval
我目前正在運行一個由 setInterval 100ms 循環的 if 語句,以在瀏覽器滾動超過 450 像素時添加和刪除類。 顯然,不循環它只會運行一次,這不是我想要的。 我聽說 setInterval 可能會滯后於瀏覽器,那么有沒有辦法更好地優化此代碼?
setInterval(function() {
if(window.scrollY > 450) {
document.querySelector('.whatever').classList.remove("whatever2);
} else {
document.querySelector('.whatever').classList.add("whatever3");
}
}, 100);
代碼以這種方式工作,但顯然我希望它盡可能優化。 我曾經使用 jQuery,並且我能夠使用 document.ready 復制它,如下所示:
$(document).ready(function(){
$(window).scroll(checkScroll);
function checkScroll() {
if($(window).scrollTop()>=450) {
$('.whatever').addClass('whatever2');
}else{
$('.whatever').removeClass('whatever3');
}
}
});
不過,我很難以更好的方式將其轉換為 JavaScript。
嘗試:
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.