CSS滚动驱动动画核心API与scroll-timeline语法
CSS滚动驱动动画(Scroll-driven Animations)是W3C规范中的重要新特性,允许将动画进度绑定到滚动位置而非时间轴。传统CSS动画基于animation-duration时间线驱动,而滚动驱动动画由scroll-timeline定义的滚动进度条驱动,无需JavaScript监听scroll事件即可实现高性能的视差滚动、进度条、揭示动画等效果。
核心语法结构:
/* 定义滚动时间线 */.scroll-container { scroll-timeline-name: --my-scroll; scroll-timeline-axis: block;}/* 将动画绑定到滚动时间线 */.animated-element { animation: fade-in linear; animation-timeline: --my-scroll; animation-range: entry 0% cover 40%;}@keyframes fade-in { from { opacity: 0; transform: translateY(50px); } to { opacity: 1; transform: translateY(0); }}
scroll-timeline-axis支持block(垂直滚动)和inline(水平滚动)两个方向。animation-range定义动画在滚动范围中的起止位置,支持entry、exit、cover、contain等关键字,精确控制元素进入视口时动画的触发时机。
view-timeline视口进度动画与range叠加
view-timeline是scroll-timeline的补充,以元素自身在滚动容器中的可见进度为时间线。区别在于:scroll-timeline基于容器的整体滚动进度(0%到100%),view-timeline基于特定元素进入和离开视口的进度。
.card { view-timeline-name: --card-view; view-timeline-axis: block; animation: reveal linear both; animation-timeline: --card-view; animation-range: entry 10% cover 30%;}
上述代码的含义是:当card元素进入视口10%位置时动画开始,到达视口30%覆盖位置时动画完成。这种方式天然适配列表逐项揭示效果,每个卡片独立跟踪自己的可视进度。
animation-range的关键字解析:entry表示元素刚进入视口,exit表示元素完全离开视口,contain表示元素完全在视口内,cover表示元素从进入视口到离开视口的完整区间。组合使用entry 0% cover 100%可以覆盖从元素出现到完全进入视口的全过程。
滚动进度条与视差滚动效果实现
页面顶部滚动进度条是scroll-timeline最典型的应用场景:
.page-progress { position: fixed; top: 0; left: 0; width: 100%; height: 3px; background: linear-gradient(90deg, #6366f1, #ec4899); transform-origin: left; animation: progress linear; animation-timeline: --page-scroll;}@keyframes progress { from { transform: scaleX(0); } to { transform: scaleX(1); }}
视差滚动效果的实现更为简洁,不同层以不同速率移动:
.parallax-bg { animation: parallax linear; animation-timeline: --page-scroll;}@keyframes parallax { from { transform: translateY(0); } to { transform: translateY(-200px); }}
浏览器兼容性与降级方案
截至2026年,Chrome 115+、Edge 115+已完整支持scroll-timeline和view-timeline。Firefox从134版本开始支持。Safari从17.4版本部分支持。不支持此特性的浏览器中动画默认不播放,可通过@supports查询提供降级方案:
@supports (animation-timeline: --test) { .card { animation: reveal linear both; animation-timeline: --card-view; }}@supports not (animation-timeline: --test) { .card { opacity: 1; transform: none; }}
性能方面,滚动驱动动画由浏览器合成器线程驱动,无需JavaScript参与主线程计算,帧率表现稳定在60fps以上,相比IntersectionObserver+JavaScript方案性能优势显著。移动端场景下,滚动驱动动画也是首选实现方式。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/css-gun-dong-qu-dong-dong-hua-scrolltimeline-yu-shi-kou/