我有一个onscroll函数,一旦你向下滚动页面就会将一个类添加到我的标题中,一旦你在顶部就回到它的原始状态。现在,该功能完美运行,但它反复查询DOM。所以,如果我向下滚动,那么" setOpaqueState"反复注入:
<div id="header1" class="setOpaqueState setOpaqueState setOpaqueState setOpaqueState"/>
甚至在向上滚动时,它会一直添加它直到我到达顶部,并且当&#34; removeOpaqueState&#34;将被添加。
我尝试使用window.scroll = null;在我的函数结束但是只保留我的标题为&#34; setOpaqueState&#34;整个
这是我的JS: window.onscroll = scroll;
function scroll() {
var header=document.getElementById("header1");
if((document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset) > 50){
header.className = header.className.replace ( /(?:^|\s)removeOpaqueState(?!\S)/g , '' );
header.className += " setOpaqueState";
}
else {
header.className = header.className.replace ( /(?:^|\s)setOpaqueState(?!\S)/g , '' ); /* REGEX-verify the above is the whole classname/ensures there is no non-space character following*/
header.className += " removeOpaqueState";
}
}