在这种情况下,目标是创建一个保留的导航栏页面加载时位于视口底部。当用户向下滚动时,导航栏应向上滚动并固定在页面顶部。
HTML 和 CSS:
<li><a href="#">Home</a></li> <li><a href="#">Services</a></li> <li><a href="#">Contact</a></li><p></ul><br></div></p> <pre class="brush:php;toolbar:false">#nav-container { position: relative; bottom: 0; width: 100%; background-color: #202020; z-index: 10; } .nav-menu { list-style-type: none; display: flex; justify-content: center; } .nav-menu > li { margin: 0 10px; } .nav-menu > li > a { color: #ffffff; text-decoration: none; padding: 10px 15px; border-radius: 5px; } .sticky { position: fixed; top: 0; }
JavaScript:
const menuElement = document.getElementById("nav-container"); window.addEventListener("scroll", () => { if (window.scrollY > 100) { menuElement.classList.add("sticky"); } else { menuElement.classList.remove("sticky"); } }); ```` This code adds the "sticky" class to the navigation bar element when scrolling down more than 100 pixels. When scrolling back up to a point where it's no longer fixed, the "sticky" class is removed. **CSS:**
/粘状态样式 /
.sticky {
背景颜色: #ffffff;
框阴影: 0px 2px 5px 0px rgba(0, 0, 0, 0.2);
}
This styling can be customized to match the desired appearance of the fixed navigation bar.
以上是如何在 Bootstrap 中创建粘性导航栏?的详细内容。更多信息请关注PHP中文网其他相关文章!