卷轴上的香草JS盒子阴影

时间:2016-09-08 14:36:17

标签: javascript css menu navigation

我一直在学习vanilla JS,这个问题的大多数解决方案依赖于jquery,我发现自己有点糊涂了。 (这不是js over jq参数,我正在寻找特定的解决方案)。

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

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

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

然后将scroll事件添加到它:

header.onscroll = function(){};

此时我在检查什么? y偏移?

2 个答案:

答案 0 :(得分:1)

这应该有帮助

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>

答案 1 :(得分:0)

您的代码绑定到header的onscroll事件,但根据您解释的内容,您可以绑定到正文的onscroll事件并检查window.scrollY < / p>

http://mdn.io/scrollY