gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:20:27 24 4
gpt4 key购买 nike

我目前正在运行一个由 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>

关于javascript - 让 JavaScript if 语句定期运行,而不是在不使用 setInterval 的情况下运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68536328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com