我已经为这个自己的项目创建了一个实用程序和主导航栏,我希望在滚动42像素时使主导航栏变为粘性。
然而,当我滚动时,导航栏没有固定在窗口顶部。我用实用程序导航进行了测试,它完美地工作了。这是我的主导航栏编码...
然而,当我滚动时,导航栏没有固定在窗口顶部。我用实用程序导航进行了测试,它完美地工作了。这是我的主导航栏编码...
$(window).on("scroll", function () {
var distanceScrolled = $(window).scrollTop();
console.log("The distance scrolled is: " + distanceScrolled);
if(distanceScrolled>42){
$("#main-nav").addClass("scrolled");
}
else{
$("#main-nav").removeClass("scrolled");
}
});
#main-nav {
position: relative;
width: 100%;
height: 100px;
background-color: #000000;
}
.main-nav-left {
list-style: none;
float: left;
padding-left: 28px;
height: 100px;
}
.main-nav-items {
position: absolute;
top: 40%;
left: 290px;
list-style: none;
text-decoration: none;
}
.main-nav-items li {
display: inline-block;
padding-right: 12px;
margin-right: 13px;
}
.main-nav-right li {
float: right;
padding-right: 12px;
margin-right: 26px;
margin-top: 40px;
list-style: none;
}
#main-nav a {
text-decoration: none;
color: #ffffff;
}
.scrolled {
position: fixed;
top: 0;
z-index: 1000;
}
<nav id="main-nav">
<ul class="main-nav-left">
<li><a href="#"><img src="images/thule_logo.png" height="100" width="auto"></a></li>
</ul>
<ul class="main-nav-items">
<li><a href="#">CARRIERS & RACKS</a></li>
<li><a href="#">ACTIVE WITH KIDS</a></li>
<li><a href="#">LUGGAGE & BAGS</a></li>
<li><a href="#">SLEEVES & CASES</a></li>
<li><a href="#">EXPLORE THULE</a></li>
</ul>
<ul class="main-nav-right">
<li><a href="#"><i class="fas fa-search fa-lg"></i></a></li>
</ul>
</nav>
<script src="js/jquery-v3.3.1.js"></script>
<script src="js/main.js"></script>
position: sticky
吗?(文档:W3C,MDN) - David Thomas