[英]Combining scroll with many if statements that change the same div
我正在尝试理解 JavaScript,但似乎无法使用if
和else if
语句正确编写函数。 我想要一个功能,我可以向下滚动页面并且div
元素的背景颜色多次更改。 所以,如果我滚动 50 像素,背景是一种颜色,然后我继续滚动直到 300 像素,它变成蓝色,然后我继续滚动直到 600 像素,它变成红色,依此类推。 这是我试图编写的代码,但它似乎不起作用。 是因为最后的else
吗? 还是因为if
之间存在矛盾?
window.onscroll = function() {myFunction()}; function myFunction() { if (document.body.scrollTop > 60 || document.documentElement.scrollTop > 60) { document.getElementById("myP").className = "test"; } else if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) { document.getElementById("myP").className = "test2"; } else if (document.body.scrollTop > 600 || document.documentElement.scrollTop > 600) { document.getElementById("myP").className = "test3"; } else { document.getElementById("myP").className = ""; } }
.test { background-color: yellow; } .test2 { background-color: red; } .test3 { background-color: blue; }
<body style="height:1500px"> <p>Scroll down this page</p> <p id="myP" style="position:fixed">hello! </p>
我认为你的问题是因为你的第一个 if 总是正确的。 因为一旦超过 60px,就会添加类测试。 你应该像这样限制它:
if ((document.body.scrollTop > 60 || document.documentElement.scrollTop > 60)
&& (document.body.scrollTop < 300 || document.documentElement.scrollTop < 300)) {
document.getElementById("myP").className = "test";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.