滚动监听应绑定到 window 而非容器元素,因静态页实际滚动主体是 window;需用 window.pageYOffset 和 document.documentElement.scrollHeight 计算进度,并通过 requestAnimationFrame 节流更新,同时监听 resize 修复 iOS Safari 的 height 变化问题。
window 而不是某个容器HTML5 静态页默认没有“内容容器”封装,阅读进度条必须监听整个页面滚动,所以事件要挂载在 window 上,而不是 document.getElementById('main') 这类元素。否则在 Safari 或部分移动端 WebView 中会失效——因为 overflow: auto 没生效,实际滚动的是 window,不是子元素。
实操建议:
window.ad
dEventListener('scroll', handler),别用 element.addEventListener('scroll', ...)
没加 overflow: hidden 或固定高度,否则 window 不会触发 scrollhandler(),避免刷新时进度条不更新scrollTop 和 scrollHeight 哪里取才准确静态页中,document.body.scrollTop 在 Chrome/Firefox 新版本里始终为 0(已被废弃),必须用 window.pageYOffset 或 document.documentElement.scrollTop;而 scrollHeight 要取 document.documentElement.scrollHeight,不能取 body.scrollHeight——后者在某些文档模式下会少头部/尾部留白高度,导致进度算到 95% 就满了。
关键判断逻辑:
document.documentElement.scrollHeight - window.innerHeight
window.pageYOffset(兼容性最好)Math.min(100, (window.pageYOffset / (document.documentElement.scrollHeight - window.innerHeight)) * 100)
直接在 scroll 里更新 width 会导致高频重绘卡顿,尤其低端安卓机。必须节流 + 使用 requestAnimationFrame 批量更新。
实操建议:
setTimeout 节流(精度差、易丢帧)let ticking = false + requestAnimationFrame 包裹更新逻辑transition: width 0.1s ease-out,比 JS 动画更省资源let ticking = false;
const progressBar = document.getElementById('progress-bar');
function updateProgress() {
const scrollTop = window.pageYOffset;
const scrollHeight = document.documentElement.scrollHeight;
const height = scrollHeight - window.innerHeight;
const progress = height <= 0 ? 100 : Math.min(100, (scrollTop / height) * 100);
progressBar.style.width = ${progress}%;
}
function requestTick() {
if (!ticking) {
requestAnimationFrame(() => {
updateProgress();
ticking = false;
});
ticking = true;
}
}
window.addEventListener('scroll', requestTick);
iOS Safari 的 window.innerHeight 在地址栏收起/展开时会变化,但 scroll 事件不触发 resize,导致分母突变,进度条跳变甚至倒退。这不是 bug,是它的 UI 行为。
应对方式:
resize 事件,重新计算一次进度(哪怕没滚动)window.innerHeight 做实时分母,改用 document.documentElement.clientHeight(更稳定)真正难处理的是首屏加载后立即滚动的场景——iOS WebKit 可能还没完成布局测量,scrollHeight 拿到的是初始值。这种情况下,延迟 100ms 再初始化进度条更稳妥。