SCROLL-DRIVEN
滚动进度Scroll Progress
用顶部细条或圆环反映页面或章节的滚动完成度,帮助用户在长文中定位;不宜遮挡内容。
效果预览
原生舞台演示;可用右侧工具重播、切换背景或窄视口。
长文示意
第二段
第三段
原生实现与推荐库对照
默认展示可离线复制的原生代码;切换到推荐库轨查看 GSAP、Motion 等开源片段。
.scroll-prog{position:sticky;top:0;height:3px;background:rgba(0,0,0,.08);z-index:2}
.scroll-prog > i{display:block;height:100%;width:100%;transform-origin:left center;transform:scaleX(var(--p,0));background:#2563eb}
@media (prefers-reduced-motion:reduce){.scroll-prog > i{transition:none}}
/* 原生 scroll + rAF */
const bar = document.querySelector(".scroll-prog > i");
function onScroll() {
const max = document.documentElement.scrollHeight - innerHeight;
const p = max > 0 ? scrollY / max : 0;
bar.style.transform = "scaleX(" + p + ")";
}
addEventListener("scroll", () => requestAnimationFrame(onScroll), { passive: true });
适合与不适合
不适合
不适合短页(高度不足一屏);进度条恒为 0 会显得多余。
和相近模式的区别
踩坑与工程要点
容易踩的坑
- 在固定头与嵌套滚动容器并存时,进度条应绑定正确的 scroll 根节点。
- 每帧写 width 会触发布局,优先 transform scaleX 或 CSS variable。
无障碍
- progressbar 需 aria-valuenow 与滚动同步。
- reduced-motion 仍可提供进度,只是不用过渡动画。
性能
- 用 scaleX 或 CSS 变量,避免每帧读写 offsetHeight。
- 嵌套滚动时绑定正确容器。
AI 提示词
顶部 3px 进度条:scaleX 0→1 映射文档 scrollTop/(scrollHeight-clientHeight);更新用 rAF 节流;reduced-motion 仍可显示静态进度(非动画属性)。
Top progress bar mapped to scrollTop ratio; throttle with requestAnimationFrame; scaleX or CSS vars preferred over layout-width animation.
相关 UI 模式
常见问题
和 mc-scroll-driven 区别?
scroll-driven 是 CSS 时间线实验特性;此条含传统 rAF 做法。
固定在顶栏下怎么放?
sticky top 等于头栏高度;或放在头栏内 absolute。