问题描述
我目前正在尝试在常规菜单栏下方实施粘性导航栏。
然而,当我向上滚动时,我的导航栏覆盖了我的菜单栏。有人可以帮我吗? :)
*/ #navbar {
overflow: hidden;
background-color: #333;
}
/* Navbar links */ #navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px;
text-decoration: none;
}
/* Page content */ .content {
padding: 16px;
}
/* The sticky class is added to the navbar with JS when it reaches its scroll position */ .sticky {
position: fixed;
top: 0;
z-index:999;
}
/* Add some top padding to the page content to prevent sudden quick movement (as the navigation bar gets a new position at the top of the page (position:fixed and top:0) */ .sticky + .content {
padding-top: 60px;
}
// 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");
}
}
<div id="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
</div>
解决方法
使用位置:粘性。
.sticky {
position:sticky;
}
看这个例子:https://www.w3schools.com/howto/howto_css_sticky_element.asp
,我认为您无需使用 javascript 即可实现这一目标。这是我使用 html 和内联 css 所做的:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Document</title>
<script src="https://kit.fontawesome.com/7b7972335d.js" crossorigin="anonymous"></script>
</head>
<body>
<div style="background-color: yellow;padding: 20px;">Menu bar</div>
<div style="background-color: greenyellow;padding: 20px;position: sticky;top:0">Navigation bar</div>
<div style="background-color: orange;padding: 20px;height: 100vh;">PAge body</div>
</body>
</html>
除非您要实现某些特定目标,否则使导航栏具有粘性并将位置设置为顶部应该可以解决此问题