我让我的导航栏只有在我向下滚动时才停留在顶部。但是当我再次向上滚动时,它会立即到达底部(这是以前的位置)。我希望我的导航栏在窗口中显示时停留在以前的位置。下面是我的代码-
- 超文本标记语言:**
<section class="section-1">
<img class="logo" src="./Assets/Asset 2@3x.png" width="320" alt="Brand Icon">
<p class="description">Luxury Jewelry Store</p>
<nav class="navbar">
<a href="#" class="navbar-link">Home</a>
<a href="#" class="navbar-link">My Cart</a>
<a href="#" class="navbar-link">My Orders</a>
<a href="#" class="navbar-link">FAQs</a>
<a href="#" class="navbar-link">About Us</a>
<div class="search">
<i class="fa-solid fa-magnifying-glass searchIcon"></i>
<input class="searchBox" placeholder="Search..." type="search">
<input type="submit" value="Search" class="searchButton">
</div>
</nav>
</section>
CSS:
.section-1{
height: 100vh;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: relative;
}
.navbar{
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 50px;
background-color: #92A9BD;
position: absolute;
bottom: 0;
transition: all 0.3s;
z-index: 1;
}
.sticky{
position: fixed;
top: 0;
left: 0;
right: 0;
}
联森:
window.onscroll = function() {
const navbar = document.querySelector(".navbar");
if (window.pageYOffset > navbar.offsetTop) {
navbar.classList.add("sticky");
} else {
navbar.classList.remove("sticky");
}
};
2条答案
按热度按时间irlmq6kh1#
你只需要把位置从固定变为粘滞
没有必要去干预权利;
mrwjdhj32#
正如@harsh-deep和@Zeikman建议的那样,我删除了JS代码,只使用sticky作为位置-
在html文件中我给nav元素添加了sticky。2真的很简单!3谢谢!