必须设置 html { scroll-behavior: smooth; },否则 window.scrollto({ top: 0, behavior: 'smooth' }) 无动画;该 css 是原生平滑滚动的强制前提,仅设在 body 无效;可检测支持性并 fallback 同步跳转;避免与第三方库(如 smooth-scroll、bootstrap 锚点)冲突。

必须设置 html { scroll-behavior: smooth; },否则 JS 行为静默失效
很多人写了 window.scrollTo({ top: 0, behavior: 'smooth' }) 却没动画,根本原因就是漏掉了这行 CSS。它不是可选优化,而是强制前提——behavior: 'smooth' 在现代浏览器中依赖该 CSS 属性启用滚动动画引擎。只写在 body 上无效;旧版 Safari(-webkit-scroll-behavior: smooth;,但当前主流环境已无需前缀。
点击按钮时必须调用 event.preventDefault()
常见错误是直接绑定 href="#top" 或 onclick="scrollToTop()",结果页面先闪一下跳到锚点位置,再执行平滑滚动。这是因为浏览器默认会响应 # 链接并立即跳转。解决方式只有两个:
- 把按钮做成
<button type="button"></button>,彻底避开锚点语义 - 若仍用
<a href="#top"></a>,必须在事件回调里调用event.preventDefault() - 推荐用
data-bs-toggle="scroll"这类自定义属性,不混用 Bootstrap 的data-bs-toggle="collapse"等已有语义
fixed 导航栏会导致内容被遮挡,需手动补偿 offset
Bootstrap 的 fixed-top 导航栏高度通常为 56px(或含阴影后更高),window.scrollTo({ top: 0 }) 会让页面顶部刚好卡在导航栏下方,第一屏内容被盖住。正确做法是减去导航栏高度:
const navbar = document.querySelector('.navbar.fixed-top');
const offset = navbar ? navbar.offsetHeight : 0;
window.scrollTo({ top: 0 - offset, behavior: 'smooth' });
注意:不能用 getComputedStyle(navbar).height,因为固定定位元素的计算高度可能为 auto;offsetHeight 更可靠。移动端键盘弹出时视口变化可能导致偏移不准,可加 setTimeout(() => ..., 100) 延迟执行。
兼容性 fallback 很简单,别引入 polyfill 库
behavior: 'smooth' 在 IE、老 Android WebView 中不支持,但没必要上完整 polyfill。检测方式极简:
if ('scrollBehavior' in document.documentElement.style) {
window.scrollTo({ top: 0, behavior: 'smooth' });
} else {
window.scrollTo(0, 0); // 同步跳转,用户几乎无感
}
真正容易被忽略的是:如果项目用了第三方平滑滚动库(如 smooth-scroll),它可能和 Bootstrap 的锚点跳转逻辑冲突,尤其当页面同时启用了 data-bs-spy="scroll"。优先砍掉这类依赖,原生方案更可控、更轻量。











