我试图让你明白,当你向下滚动1500(像素?(时,底部的绝对div消失,然后如果向上滚动(滚动顶部回到1500以下(会重新出现。
不知道为什么,但是每当滚动顶部超过1500时,div似乎会随机闪烁; 它应该消失,并在回到范围内时重新出现。
为什么效果会出现故障?它应该只是切换显示它的类。感谢您的任何帮助。
window.onscroll = function() {if ((window.innerHeight + window.scrollY) >= 1500) {document.getElementById('test').classList.toggle("customstyle")}};
body {
height: 2000px;
background: #ccc;
}
.customstyle {display: none}
<body>
<div id="test" style="
position: fixed;
bottom: 0;
background: red;
left: 0;
padding: 20px;
width: 100%;
text-align: center;
">text</div>
</body>
如果条件为真,您说的是切换类,以便每次检查时它都在切换类,当它为真时,它会闪烁。
您希望使用布尔值作为第二个参数。
document.getElementById('test').classList.toggle("customstyle", window.innerHeight + window.scrollY >= 1500)
因为您正在切换类(因此每次在超过 1500 像素时调用滚动事件时都会添加和删除类(,所以您应该在超过 1500 像素时添加类,然后在低于 1500 像素时将其删除:
window.onscroll = function() {
if ((window.innerHeight + window.scrollY) >= 1500) {
document.getElementById('test').classList.add("customstyle");
} else {
document.getElementById('test').classList.remove("customstyle");
}
};
window.onscroll = function() {
if (window.scrollY >= 1500) {
document.getElementById('test').classList.add("customstyle")
} else {
document.getElementById('test').classList.remove("customstyle")
}
};
body {
height: 2000px;
background: #ccc;
}
.customstyle {display: none}
<body>
<div id="test" style="
position: fixed;
bottom: 0;
background: red;
left: 0;
padding: 20px;
width: 100%;
text-align: center;
">text</div>
</body>