将滚动与许多更改相同div的{if}语句结合使用

时间:2018-03-12 12:34:29

标签: javascript if-statement

我试图理解js,似乎我无法使用if和else if语句正确编写函数。 我希望有一个功能,我向下滚动页面,div的背景颜色改变多次。所以如果我滚动50px是一种颜色,那么我一直滚动到300px并且它是蓝色的,然后我一直滚动到600px并且它是红色的,依此类推。 这是我试图编写的代码,但它似乎不起作用。是因为最后的“其他”?还是因为“ifs”之间存在矛盾? 谢谢。

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>

1 个答案:

答案 0 :(得分:0)

我认为你的问题是因为你的第一个if总是如此。因为一旦你超过60px,你就会增加课堂测试。你应该这样限制它:

if ((document.body.scrollTop > 60 || document.documentElement.scrollTop > 60)
     && (document.body.scrollTop < 300 || document.documentElement.scrollTop < 300)) {
        document.getElementById("myP").className = "test";
}