用 CSS 滚动驱动动画替代 scroll 监听

animation-timeline 让「随滚动变化」的效果不再需要 JavaScript。这篇文章用阅读进度条和首屏渐隐两个例子,讲清楚它的用法和降级方案。

目录 · 3 节
  1. scroll() 时间线
  2. 渐进增强
  3. 小结

过去要做一个阅读进度条,几乎都要监听 scroll 事件再用 requestAnimationFrame 节流。现在,一段 CSS 就够了。

scroll() 时间线

progress.css
.progress {
transform-origin: 0 50%;
animation: grow linear both;
animation-timeline: scroll(root);
}
@keyframes grow {
from { transform: scaleX(0); }
to { transform: scaleX(1); }
}

渐进增强

不支持的浏览器怎么办?用 @supports 包起来,再准备一个 JS 回退:

if (!CSS.supports('animation-timeline: scroll()')) {
// 用 rAF 节流的 scroll 监听设置 CSS 变量
}

小结

能交给 CSS 的动效,就不要交给 JavaScript:主线程会感谢你。