1 回答

TA贡献1865条经验 获得超7个赞
您需要设置.dropdown-content
到position: fixed
时,导航栏是粘
见下文
//STICKY HEADER
// When the user scrolls the page, execute myFunction
window.onscroll = function() {fixHeader();};
// Get the header
var header = document.getElementById("sticky_header");
// Get the offset position of the navbar
var sticky = header.offsetTop;
// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
function fixHeader() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
.navbar {
width: 100%;
overflow: hidden;
background-color: darkred;
font-family: monospace;
text-transform: uppercase;
box-shadow: 0px 10px 17px 0px black;
}
/* Links inside the navbar */
.navbar a {
float: left;
font-size: 16px;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
border-right: 2px solid white;
}
/* The dropdown container */
.dropdown {
float: left;
overflow: hidden;
text-transform: uppercase;
}
/* Dropdown button */
.dropdown .dropbtn {
font-size: 16px;
border: none;
outline: none;
color: white;
padding: 14px 16px;
background-color: inherit;
font-family: inherit; /* Important for vertical align on mobile phones */
margin: 0; /* Important for vertical align on mobile phones */
}
/* Add a red background color to navbar links on hover */
.navbar a:hover, .dropdown:hover .dropbtn {
background-color: #002500;
}
/* Dropdown content (hidden by default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
/* Links inside the dropdown */
.dropdown-content a {
float: none;
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
border-bottom: 2px dotted #ccc;
}
/* Add a grey background color to dropdown links on hover */
.dropdown-content a:hover {
background-color: #002500;
border-bottom: 2px dotted #002500;
color: white;
}
/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content {
display: block;
}
.sticky {
position:fixed;
}
/* show the dropdown when sticky*/
.sticky .dropdown-content {
position:fixed;
}
<div class="navbar" id="sticky_header">
<a href="#home">Home</a>
<a href="#news">News</a>
<div class="dropdown">
<button class="dropbtn">Dropdown
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
</div>
<div style="height:200vh">Dummy content</div>
添加回答
举报