滚动上的香草JS框阴影

Vanilla JS Box Shadow on Scroll

本文关键字:阴影 JS 香草 滚动      更新时间:2023-09-26

我一直在学习香草JS,这个问题的大多数解决方案都依赖于jquery,我发现自己有点困惑。(这不是js对jq的争论,我正在寻找一个具体的解决方案)。

我正在尝试创建一个在滚动时激活固定位置菜单的方框阴影。

如果我在变量中捕获header元素,

var header = document.getElementById("header");

,然后添加滚动事件:

header.onscroll = function(){};

我在这里检查什么?y ?

这应该有帮助

window.onscroll = function() {myFunction()};
function myFunction() {
    if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
        document.getElementById("fixedMenu").className = "myFixedMenu-box-shadow";
    } else {
        document.getElementById("fixedMenu").className = "myFixedMenu";
    }
}
body{
height: 900px;
}
.myFixedMenu{
width : 100%;
height: 70px;
background-color: black;
position: fixed;}
.myFixedMenu-box-shadow{
  width : 100%;
height: 70px;
background-color: orange;
  position: fixed;
  box-shadow: 0px 0px 5px 5px #e1e1e1;
}
<div class="myFixedMenu" id="fixedMenu">
Some Menu Item
</div>

您的代码绑定到header的onscroll事件,但根据您所解释的,您可以绑定到主体的onscroll事件并检查window.scrollY

http://mdn.io/scrollY