我正在尝试使我的垂直导航栏在用户滚动时移至顶部(原始位置不在顶部)。我只知道HTML,CSS和JavaScript,所以我不知道JQuery。这是导航栏的代码:
类或ID名称有问题,还是JavaScript代码?
var body = document.getElementsByTagName("body")[0];
var navigation = document.getElementById("navigation");
window.addEventListener("scroll", navigationFixing());
function navigationFixing() {
if (body.scrollTop > navigation.getBoundingClientRect().bottom)
{navigation.className = "fixedNavigation";
}
else {
navigation.className = "notFixedNavigation";
}
}
#navigation {list-style-type: none;
width: 15%;
margin: 0px;
padding: 0px;
font-size: 35px;
border: 1px solid;
height: 100%;
background-color: #d6d6c2;
overflow: auto;
position: absolute;
}
.navigationbar {
border-bottom: 1px solid black;
}
.navigationbar a {display: block;
background-color: #C0C0C0;
padding-left: 10px;
padding-bottom: 16px;
text-decoration: none;
color: #ffffff;
}
.navigationbar a:hover {background-color: #404040;
color: white;}
.navigationbar a.nuvarande {background-color: black;
}
.fixedNavigation {
position: fixed;
top: 0;
left: 0;
}
.notFixedNavigation {
position: absolute;
}
<ul id="navigation" class="notFixedNavigation">
<li class="navigationbar">
<a href="index.html">Home</a>
</li>
<!---------------DATOR-------------------
<li class="navigationbar">
<a href="play.html">Play</a>
</li>
---------------------------------------->
<li class="navigationbar">
<a href="" class="nuvarande">Rules</a>
</li>
<li class="navigationbar">
<a href="tactics.html">Tactics</a>
</li>
<li class="navigationbar">
<a href="contact.html">Contact</a>
</li>
</ul>
您关心立即致电事件处理程序,而不是将其附加到侦听器上。删除Parens。
window.addEventListener("scroll", navigationFixing);
此外,当位置更改时,navigation.getBoundingClientRect().bottom
将更改。最好将其设置在功能之外。
var pos = navigation.getBoundingClientRect().bottom;
function navigationFixing() {
if (body.scrollTop > pos) {...}
}
另外,@bestinamir的注意事项,您的CSS被覆盖。它需要一些工作,但是您可以从:
开始.fixedNavigation {
position: fixed !important;
top: 0;
left: 0;
}