我当前正在运行一个以 setInterval 100ms 循环的 if 语句,以便在浏览器滚动超过 450px 时添加和删除类。显然,不循环它只会运行一次,这不是我想要的。我听说 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>
关于javascript - 让 JavaScript if 语句定期运行而不是一次而不使用 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68536328/