我试图在向下滚动时让导航栏保持在顶部。 当导航栏位于顶部时很容易,但由于我在其上方放置了一个 Div,所以我似乎无法弄清楚。我试过位置固定,其他的没有用。 例如像这个网站 www.screencult.com。顺便说一句,我正在使用 Bootstarp。
这是我目前所拥有的 This is what I have
<div id="nav" class="navbar navbar-default navbar-fixed">
<div class="container">
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#description" id="color" >ABOUT US</a></li>
<li><a id="color" href="#" >GALLERY</a></li>
<li><a id="color" href="#contactus" >CONTACT US</a></li>
</ul>
</div>
</div>
</div>
#nav {
background-color: white;
border: none;
border-style: none;
}
#color {
color: #b5be35;
cursor: pointer;
transition: color 0.5s ease;
}
#color:hover {
color: #a1a5a2;
}
最佳答案
滚动到页面上的某个点后,您需要更改为固定位置。例如图像的高度。
我们使用 scroll even 监听器和 scroll top 来找出我们滚动了多远
window.addEventListener("scroll", function(e){
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
//If we have scrolled far enough on the page to be past the image
//Change the nav to have fixed positioning
var imageHeight = document.getElementById("image-header").clientHeight
var nav = document.getElementById("nav");
if(scrollTop > imageHeight){
nav.classList.add("fixed-nav");
}
else{
nav.classList.remove("fixed-nav");
}
});
关于javascript - 在 HTML 中向下滚动时将导航栏移动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386244/