[英]I'm trying to make my navbar fixed when the user scrolls down, but when I scroll down it doesn't stay
I'm trying to make it so that when the user starts scrolling, the navbar becomes fixed at the top.我试图做到这一点,以便当用户开始滚动时,导航栏固定在顶部。 I'm using vanilla javascript to add my fixed navbar class dynamically on a scroll event, and when I check the devtools the class is being added, but the navbar doesn't change, so I'm assuming the issue is with my CSS.
我正在使用 vanilla javascript 在滚动事件上动态添加我的固定导航栏类,当我检查 devtools 正在添加该类时,但导航栏没有改变,所以我假设问题出在我的 CSS 上。 Any help is appreciated.
任何帮助表示赞赏。
const navbar = document.querySelector(".navbar"); // fixed navbar on scroll window.addEventListener("scroll", () => { if (window.scrollY > 80) { navbar.classList.add(".navbar-fixed"); } else { navbar.classList.remove(".navbar-fixed"); } });
.navbar-fixed { position: fixed; top: 0; left: 0; width: 100%; background: white; color: black; z-index: 2; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); } .nav-container { display: flex; align-items: center; justify-content: space-between; max-width: 1100px; margin: 0 auto; padding: 0 30px; height: 100%; } .nav { list-style-type: none; display: flex; background: transparent; }
<!-- NAVBAR --> <div class="bg-img"> <nav id="home" class="navbar"> <div class="nav-container"> <div class="nav-logo">Logo</div> <ul class="nav"> <li> <a href="#home">Home</a> </li> <li> <a href="#about">About</a> </li> <li> <a href="#">Events</a> </li> </ul> </div> </nav> <div style="height: 1000px"></div> </div> <!-- END OF NAVBAR -->
Pretty close, just remove the dot when you add and remove the classList of navbar:非常接近,只需在添加和删除导航栏的 classList 时删除点:
const navbar = document.querySelector(".navbar"); // fixed navbar on scroll window.addEventListener("scroll", () => { if (window.scrollY > 80) { navbar.classList.add("navbar-fixed"); } else { navbar.classList.remove("navbar-fixed"); } });
const navbar = document.querySelector("#home");
// fixed navbar on scroll
window.addEventListener("scroll", () => {
if (window.scrollY > 80) {
navbar.classList.add("navbar-fixed");
} else {
navbar.classList.remove("navbar-fixed");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.