判断导航条是否过顶应监听 scroll 事件,用 getBoundingClientRect().top 动态获取其距视口顶部距离,结合 requestAnimationFrame 优化性能;iOS Safari 中 sticky 导航条需加容差判断 top ≤ 1。

滚动时如何用 scroll 事件判断导航条是否过顶
关键不是监听任意滚动,而是检测页面顶部距视口的距离是否小于导航条高度。直接读 window.scrollY 最可靠,比 document.documentElement.scrollTop 兼容性更好,也避开 IE 的怪异模式问题。
常见错误是用 offsetTop 硬编码导航条位置——一旦页面结构变化(比如加了 banner 或 margin),逻辑就崩了。正确做法是用 getBoundingClientRect() 动态获取导航条顶部坐标:
const navbar = document.querySelector('.navbar');
const handleScroll = () => {
const { top } = navbar.getBoundingClientRect();
if (top <= 0) {
navbar.classList.add('scrolled');
} else {
navbar.classList.remove('scrolled');
}
};
window.addEventListener('scroll', handleScroll);
注意:别在 scroll 里直接操作样式,只切类名;过渡效果全交给 CSS 控制,避免 JS 强制重排。
.navbar.scrolled 类该设置哪些 CSS 属性才不破坏 Bootstrap 布局
Bootstrap 的 .navbar 默认有背景透明、阴影和 padding,直接覆盖 background-color 容易导致子元素(如 brand 文字、下拉菜单)颜色不协调。必须同步调整文字色、边框、阴影强度。
立即学习“前端免费学习笔记(深入)”;
过渡要加在 background-color 和 box-shadow 上,但不能加 all——否则 hover 动画会打架。推荐写法:
.navbar {
transition: background-color 0.3s ease, box-shadow 0.3s ease;
}
.navbar.scrolled {
background-color: #fff !important;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
color: #333;
}
.navbar.scrolled .navbar-brand,
.navbar.scrolled .nav-link {
color: #333 !important;
}
要点:
- 用
!important覆盖 Bootstrap 的默认background: none和color: inherit - 确保
.nav-link在.scrolled下也有对应颜色规则,否则悬停时仍显示原色 - 移动端折叠菜单的 toggle 按钮(
.navbar-toggler)也要单独处理颜色,否则在白色背景上消失
为什么 requestAnimationFrame 包裹 scroll 处理函数很重要
滚动事件高频触发(每秒几十次),不节流会导致 CPU 占用飙升,尤其在低端设备上卡顿明显。用 setTimeout 或 debounce 会引入延迟,造成“滚动到底部才变色”的滞后感。
requestAnimationFrame 是最优解:它把判断逻辑塞进浏览器下一帧绘制前,既保证响应及时,又天然限频到 60fps。
let ticking = false;
const updateNavbar = () => {
const { top } = navbar.getBoundingClientRect();
navbar.classList.toggle('scrolled', top <= 0);
ticking = false;
};
const handleScroll = () => {
if (!ticking) {
requestAnimationFrame(updateNavbar);
ticking = true;
}
};
这个模式比纯 scroll + setTimeout 更顺滑,且无需额外依赖库。
移动端 Safari 中 position: sticky 导航条滚动变色失效怎么办
如果导航条用了 .navbar-sticky-top,iOS Safari 可能不触发 scroll 事件(因为 sticky 元素自身不滚动,而是容器滚动)。此时 getBoundingClientRect().top 依然有效,但要注意:Safari 对 position: sticky 元素的 top 计算有时返回小数,建议加容差判断:
if (top <= 1) { // 不用 strict === 0
navbar.classList.add('scrolled');
} else {
navbar.classList.remove('scrolled');
}
另一个坑是 iOS Safari 的 scroll-behavior: smooth 会影响 scroll 事件频率,若页面有锚点跳转,建议在 上禁用:scroll-behavior: auto。
最麻烦的是:某些安卓 WebView(尤其旧版)根本不支持 getBoundingClientRect() 在 sticky 元素上的精确计算。这时得 fallback 到 window.scrollY > 50 这类阈值判断——虽然不严谨,但至少可用。


















