滚动时切换Header/Navbar元素的JavaScript实现问题
滚动时动态切换Header的.is-active类解决方案
我尝试用JavaScript给header添加.is-active类,手动添加这个类时样式正常生效,但用JS实现时遇到问题。需求是:页面开始滚动时给header加上.is-active类,回到页面顶部时移除这个类。以下是相关HTML和CSS代码:
HTML代码
<header class="header"> <div class="header-nav flex container"> <figure class="header-logo"> <a href="#"> <img class="header-logo-light" src="images/logoWhite.png" alt="San Miguel Services Logo"> <img class="header-logo-dark" src="images/logoDark.png" alt="San Miguel Services Logo"> </a> </figure> <nav class="header-menu flex"> <div class="header-menu-li"> <a href="">WELCOME</a> <a href="">SERVICES</a> <a href="">ABOUT</a> <a href="">PORTFOLIO</a> <a href="">CONTACT</a> </div> </nav> <div class="header-btn"> <button href="#" class="button header-btn">REQUEST A QUOTE</button> </div> </div> </header>
CSS代码
.header { position: fixed; z-index: 1; width: 100vw; line-height: 18px; } .header .header-logo-dark { opacity: 0; display: none; } .header .header-logo-light { opacity: 1; display: block; } .header.is-active .header-logo-dark { opacity: 1; display: block; } .header.is-active .header-logo-light { opacity: 0; display: none; } .header.is-active .header-menu-li a { color: $darkBlue; &::before { background: linear-gradient(to right, $mediumGreen, $lightGreen); } } .header.is-active .header-btn button { background: $mediumGreen; color: $white; transition: 300ms ease-in-out; &:hover { box-shadow: inset 0 0 0 2px $darkBlue; color: $darkBlue; background: transparent; } } .header.is-active { background: $white; } .header-nav { padding: 20px 5.5%; position: relative; justify-content: space-between; margin: auto; } .header-logo { position: relative; a img { height: 46px; } } .header-menu { align-items: center; } .header-menu-li { a { position: relative; margin: 0 0.625rem; font-weight: 500; font-size: $font-sm; color: $white; transition: color 300ms ease-in-out; &::before { content: ""; display: block; position: absolute; height: 5px; background: $white; left: 0; right: 0; bottom: -33px; opacity: 0; transition: opacity 300ms ease-in-out; } &:hover { opacity: 0.95; &::before { opacity: 1; } } } } .header-btn { height: 46px; font-size: $font-sm; font-weight: 500; button { background: transparent; border: 1px solid $white; transition: 200ms ease-in-out; &:hover { background: $white; color: $darkBlue; } } }
解决方案
实现逻辑
监听页面滚动事件,通过window.scrollY判断当前滚动距离:
- 滚动距离大于0时,为header添加
.is-active类 - 滚动距离等于0(回到顶部)时,移除该类
完整JavaScript代码
const header = document.querySelector('.header'); function handleScroll() { if (window.scrollY > 0) { header.classList.add('is-active'); } else { header.classList.remove('is-active'); } } // 绑定滚动事件 window.addEventListener('scroll', handleScroll); // 页面加载时初始化状态 handleScroll();
代码说明
document.querySelector('.header'):准确获取目标header元素window.scrollY:获取当前页面垂直滚动的像素值classList.add()/classList.remove():安全操作类名,避免重复添加同一类的问题- 页面加载时执行
handleScroll():确保页面刷新后,即使处于滚动状态,header样式也能正确显示
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

