CSS Scroll-Driven Animations 详解一、Scroll-Driven Animations 概述CSS Scroll-Driven Animations 是 CSS 动画的一种新形式允许动画进度由滚动位置驱动。这意味着动画会随着用户滚动页面而自动更新。1.1 基本概念Scroll Timeline- 基于滚动位置的时间线View Timeline- 基于元素在视口中可见性的时间线Animation Range- 动画生效的滚动范围二、基本用法2.1 定义滚动时间线keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .element { animation: fadeIn 1s linear; animation-timeline: scroll(); }2.2 配置滚动范围.element { animation: slideIn 1s linear; animation-timeline: scroll(root block); animation-range: entry 0% exit 100%; }三、Scroll Timeline 类型3.1 scroll() 时间线/* 使用根滚动容器 */ .element { animation-timeline: scroll(); } /* 指定滚动容器 */ .element { animation-timeline: scroll(nearest); animation-timeline: scroll(root); animation-timeline: scroll(#scroll-container); }3.2 view() 时间线.element { animation-timeline: view(); animation-range: cover 0% cover 100%; }四、动画范围4.1 关键字范围/* 元素进入视口时开始完全退出时结束 */ .element { animation-range: entry 0% exit 100%; } /* 元素完全进入视口时开始开始退出时结束 */ .element { animation-range: entry 100% exit 0%; } /* 元素覆盖整个视口时 */ .element { animation-range: cover 0% cover 100%; }4.2 自定义范围.element { animation-range: 200px 400px; animation-range-start: 200px; animation-range-end: 400px; }五、实战案例5.1 滚动淡入效果keyframes fadeInUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } } .scroll-fade-in { animation: fadeInUp 1s ease-out; animation-timeline: view(); animation-range: entry 0% entry 100%; }5.2 视差滚动.parallax-layer { animation: parallax 1s linear; animation-timeline: scroll(); } keyframes parallax { from { transform: translateY(0); } to { transform: translateY(-50px); } }5.3 进度指示器.progress-bar { height: 4px; background: #667eea; animation: progress 1s linear; animation-timeline: scroll(); animation-range: 0% 100%; } keyframes progress { from { width: 0%; } to { width: 100%; } }5.4 图片画廊视差.gallery-item { animation: scaleUp 0.5s ease-out; animation-timeline: view(); animation-range: cover 0% cover 100%; } keyframes scaleUp { from { transform: scale(0.8); } to { transform: scale(1); } }六、JavaScript 集成6.1 创建滚动时间线const timeline new ScrollTimeline({ source: document.querySelector(#scroll-container), orientation: block, }); element.animate( { opacity: [0, 1] }, { duration: 1000, timeline: timeline, } );6.2 监听滚动进度const observer new IntersectionObserver( (entries) { entries.forEach((entry) { const progress entry.intersectionRatio; element.style.opacity progress; }); }, { threshold: 0.1 } ); observer.observe(element);七、浏览器兼容性属性ChromeFirefoxSafariEdgeScroll-Driven Animations11512217.4115八、总结Scroll-Driven Animations 是创建滚动动画的现代方式Scroll Timeline- 基于滚动位置View Timeline- 基于视口可见性动画范围- 精确控制动画触发时机JavaScript 集成- 更精细的控制视差效果- 创建沉浸式体验合理使用可以提升用户体验。