window.scrollto() 是最直接、兼容性最好的滚到底部方式,需传入 document.body.scrollheight 并设 behavior: 'smooth',注意 fixed 头部偏移及 dom 渲染时机。

window.scrollTo() 是最直接、兼容性最好的方式,不需要额外库或复杂逻辑。
用 window.scrollTo() 滚到底部
页面底部的纵坐标就是 document.body.scrollHeight,把它传给 window.scrollTo() 即可:
document.querySelector('#go-bottom-btn').addEventListener('click', () => {
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth'
});
});
- 必须用
behavior: 'smooth'才有滚动动画,否则是瞬移 - 别写
document.documentElement.scrollHeight—— 在某些浏览器(如 Safari)里它可能不准,document.body.scrollHeight更稳 - 如果页面用了
height: 100vh或min-height: 100vh的布局,确保内容真实撑开高度,否则scrollHeight可能偏小
为什么不用 scrollIntoView()?
有人会想:找一个页面最底端的元素,然后调用它的 scrollIntoView()。这在多数情况下可行,但容易踩坑:
- 目标元素要是已渲染且
display: block(不能是display: none或visibility: hidden) - 如果底部是动态加载的内容(比如分页后追加),那个“最底元素”可能还没存在,调用就静默失败
-
scrollIntoView({ block: 'end' })在部分旧版 Chrome 中对body不生效,行为不一致 - 需要提前在 HTML 末尾放一个占位
<div id="bottom-anchor"></div>,多一步维护
移动端和 fixed 头部要注意什么?
如果你页面顶部有 position: fixed 的 header,而你希望滚动后内容不被遮挡,window.scrollTo() 本身不处理偏移 —— 它只管绝对位置。这时候要手动补偿:
const header = document.querySelector('.header');
const offset = header ? header.offsetHeight : 0;
window.scrollTo({
top: document.body.scrollHeight - window.innerHeight + offset,
behavior: 'smooth'
});
- 减去
window.innerHeight是为了让“底部”刚好贴到视口底边,而不是滚过头 - 加上
offset是把 fixed header 的高度“还”回来,避免内容被遮住 - 这个计算只在需要视觉对齐时才加;纯功能型“到底部”可省略
真正容易被忽略的是:滚动目标是否依赖 DOM 渲染时机。比如按钮在 SPA 路由切换后才挂载,或底部内容由异步请求填充 —— 这时得等 requestAnimationFrame 或 setTimeout(..., 0) 确保 DOM 已更新,再读取 scrollHeight。否则值可能还是旧的。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











