知识点: 滚动驱动动画是 CSS 即将推出的革命性特性(Chrome 115+ 已支持),通过将动画进度与滚动容器深度绑定,实现无需 JavaScript 的视差滚动、阅读进度指示等高级效果。
一、什么是滚动驱动动画?
滚动驱动动画将传统时间轴(Time-based)动画转变为空间轴(Scroll-based)动画,实现:
- 元素动画与滚动位置精确联动
- 容器内滚动与外层滚动嵌套控制
- 完全基于 CSS 的性能优化方案
二、核心语法解析
/* 定义动画时间轴类型 */
animation-timeline: scroll(); /* 默认沿块轴滚动 */
animation-timeline: scroll(inline); /* 水平滚动轴 */
/* 指定滚动容器(默认就近祖先) */
animation-timeline: scroll(nearest);
animation-timeline: scroll(root); /* 根视口滚动 */
/* 动画进度映射规则 */
animation-range: entry 0% exit 100%;
/* 滚动开始到结束对应动画 0% 到 100% */
三、实战开发案例
<!-- 阅读进度指示条 -->
<div class="progress"></div>
<style>
.progress {
height: 3px;
background: blue;
animation: grow auto linear;
animation-timeline: scroll(root);
}
@keyframes grow {
from { width: 0% }
to { width: 100% }
}
</style>
<!-- 视差滚动效果 -->
<div class="parallax"></div>
<style>
.parallax {
animation: move 1s linear;
animation-timeline: scroll();
animation-range: 0% 50%;
}
@keyframes move {
from { transform: translateY(0) }
to { transform: translateY(-100px) }
}
</style>
四、开发中的黄金法则
- 性能优先:优先使用
transform
/opacity
避免重绘 - 回退方案:通过
@supports
提供传统滚动监听方案 - 容器隔离:嵌套滚动时使用
container-type: inline-size
建立容器查询 - 时间轴混合:与
@scroll-timeline
旧语法并存时需做兼容处理
五、常见问题排查
问题现象: 动画未随滚动触发
解决方案:
- 检查容器是否具有
overflow: scroll
属性 - 确认元素与滚动容器的层级关系
- 使用 DevTools 的 Animations 面板调试时间轴
- 验证浏览器支持情况(chrome://flags 开启实验性功能)
六、未来扩展方向
- 元素间交叉检测:结合
Intersection Observer
实现精准触发 - 路径滚动动画:基于
scroll(path)
的非线性动画 - 分页式滚动:与
@media (scroll-snap-type)
联动
那我问你,那我问你:
如何实现一个「滚动到容器中部时元素旋转,继续滚动到末尾时复位」的效果?要求不依赖 JavaScript。
(答案提示:使用 animation-range
分割动画阶段)