我正在尝试使用 CSS 和 JavaScript 在滚动时制作一个粘性导航栏,但它显示为普通导航栏,并且在滚动时不粘。滚动时如何让它粘住?我在代码中添加了标题
window.onscroll = function() {
myFunction()
};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
#navbar {
overflow: hidden;
background-color: #333;
}
/* Navbar links */
#navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px;
text-decoration: none;
}
.sticky {
position: fixed;
top: 0;
width: 100%;
}
.sticky+.content {
padding-top: 60px;
}
<div class="header">
<h2>S I U</h2>
<p>T h e f u t u r e & B e y o n d</p>
</div>
<div id="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
</div>
最佳答案
快到了!您需要将 .sticky
类应用到您的导航,以使其固定。
window.onscroll = function() { myFunction() };
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
body {
height: 10000px;
}
#navbar {
overflow: hidden;
background-color: #333;
}
/* Navbar links */
#navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px;
text-decoration: none;
}
.sticky {
position: fixed;
top: 0;
width: 100%;
}
.sticky+.content {
padding-top: 60px;
}
<div class="header">
<h2>Scroll Down</h2>
<p>Scroll down to see the sticky effect.</p>
</div>
<div id="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
</div>
关于javascript - 如何创建粘性导航栏 css 和 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54681327/