【发布时间】:2018-12-08 01:49:51
【问题描述】:
我试图让导航栏粘在滚动条上我已经应用了我在 w3schools 上找到的内容,并在这里查看了一些帖子,但我没有让它工作。我的代码笔是: https://codepen.io/robot_head/full/qKQwqe/
我的代码如下
html:
<header class="header-logo">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">client</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#info">Info</a></li>
</ul>
</div>
</div>
</nav>
<div class="header-img">
<img src="img/logo.jpg" class="img-responsive" style="width:100%" alt="Image">
</div>
</header>
css:
.sticky {
position: fixed;
top: 0;
width: 100%;
}
JS:
// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};
// Get the navbar
var navbar = document.getElementById("navbar");
// Get the offset position of the navbar
var sticky = navbar.offsetTop;
// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
【问题讨论】:
-
你在使用引导程序吗?
-
是的 bootstrap-4
-
为什么不将固定顶部引导类添加到您的导航组件中?
-
另外,您正在使用 getElementById 来查找与您的 html 中的任何元素都不匹配的 id。
标签: javascript html css bootstrap-4