猿问

在特定滚动位置添加阴影

我编写了一个函数,当存在特定的滚动位置时,该函数会为元素提供阴影。所以我想在滚动位置大于 40 时给第一个元素一个阴影。当你继续滚动时,当滚动位置大于 90 时,第二个元素将得到一个阴影。但是,这适用于第一个元素但是不是第二个:即使滚动偏移量大于 90,第一个元素仍然有阴影。


window.addEventListener("scroll", function(event) {

       var scroll = this.scrollY;

       if (scroll > 40)

            {document.getElementById("Gegevens").style.boxShadow="0px 0px 45px -4px rgba(0,0,0,0.35)";

            document.getElementById("Uren").style.boxShadow=""}

       else if (scroll > 90)

            {document.getElementById("Gegevens").style.boxShadow="";

            document.getElementById("Uren").style.boxShadow="0px 0px 45px -4px rgba(0,0,0,0.35)"}

       else 

            {document.getElementById("Gegevens").style.boxShadow="";

             document.getElementById("Uren").style.boxShadow=""}

    }) 


素胚勾勒不出你
浏览 123回答 1
1回答

慕丝7291255

如果滚动偏移量大于 90,程序仍将进入第一种情况,因为(显然)大于 90 的数字也必须大于 40。这将导致该else if部分被跳过,第一个元素将始终被关注。要解决此问题,您可以:移动.之前的> 90部分。这样,如果它大于 90,它将进入那种情况,并跳过其他情况:> 40window.addEventListener("scroll", function(event) {&nbsp; &nbsp; &nbsp;var scroll = this.scrollY;&nbsp; &nbsp; &nbsp;if (scroll > 90)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {document.getElementById("Gegevens").style.boxShadow="";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("Uren").style.boxShadow="0px 0px 45px -4px rgba(0,0,0,0.35)"}&nbsp; &nbsp; &nbsp;else if (scroll > 40)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {document.getElementById("Gegevens").style.boxShadow="0px 0px 45px -4px rgba(0,0,0,0.35)";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("Uren").style.boxShadow=""}&nbsp; &nbsp; &nbsp;else&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {document.getElementById("Gegevens").style.boxShadow="";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;document.getElementById("Uren").style.boxShadow=""}})&nbsp;添加另一个条件来检查它是否足够大以容纳第二个元素:window.addEventListener("scroll", function(event) {&nbsp; &nbsp; &nbsp;var scroll = this.scrollY;&nbsp; &nbsp; &nbsp;if (scroll > 40 && scroll <= 90)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {document.getElementById("Gegevens").style.boxShadow="0px 0px 45px -4px rgba(0,0,0,0.35)";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("Uren").style.boxShadow=""}&nbsp; &nbsp; &nbsp;else if (scroll > 90)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {document.getElementById("Gegevens").style.boxShadow="";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("Uren").style.boxShadow="0px 0px 45px -4px rgba(0,0,0,0.35)"}&nbsp; &nbsp; &nbsp;else&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {document.getElementById("Gegevens").style.boxShadow="";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;document.getElementById("Uren").style.boxShadow=""}})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答