这个在某些情况会使用,可以看我的网站效果。下面是个示例。
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="navbar" id="navbar">
Navigation Bar
</div>
<div style="height: 1500px;">
<!-- Placeholder content to make the page scrollable -->
</div>
</body>
</html>
JS
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
var navbar = document.getElementById("navbar");
if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) {
navbar.classList.add("scrolled");
} else {
navbar.classList.remove("scrolled");
}
}
CSS
.navbar {
background-color: transparent;
transition: background-color 0.5s;
position: fixed;
width: 100%;
top: 0;
z-index: 1000;
}
.navbar.scrolled {
background-color: red;
}