交错动画可提供一种有趣的效果,即多个有序元素按顺序播放动画,每个元素之间略有延迟,而不是所有元素同时播放动画。这种技术通常用于列表、图库或导航菜单,以引导用户的视线,并为互动增添精致、有节奏感的效果。
使用 sibling-index() 交错动画
对 animation-delay 属性使用 sibling-index() 属性,以便每个元素的动画都按与其在父级中的位置成比例的数字进行偏移。sibling-index() 函数会返回一个整数,因此必须乘以时间单位才能将其转换为时间。
#stagger-list > .item {
--stagger-time: 0.1s;
/* Define the animation first */
animation: fade-in 0.4s;
/* Set the `animation-delay` to a time multiplied by the `sibling-index()` */
animation-delay: calc(sibling-index() * var(--stagger-time))
}
强制性要求:尊重用户偏好,为偏好减少动画效果的用户停用动画。
@media (prefers-reduced-motion: reduce){
/* Disable animation for users who prefer reduced motion. */
#stagger-list > .item {
animation: none;
}
}
后备策略
使用 CSS(通过 @supports (animation-delay: calc(sibling-index() * 0.1s)){})或 JavaScript(通过 !CSS.supports('animation-delay: calc(sibling-index() * 0.1s)'))测试对 sibling-index() 的支持。
如需在旧版浏览器中支持交错动画,请使用 JavaScript 为每个同级元素添加 --sibling-index 自定义属性。强制性:请将其封装在 CSS.supports('animation-delay: calc(sibling-index() * 0.1s)') 测试中,以避免运行不必要的 JavaScript。
if(!CSS.supports('animation-delay: calc(sibling-index() * 0.1s)')){
const staggerList = document.getElementById('stagger-list');
[...staggerList.children].forEach((el, index)=>el.style.setProperty('--sibling-index', index + 1));
}
添加一个使用 --sibling-index 自定义属性的 animation-delay 声明。它必须位于使用 sibling-index() 函数的 animation-delay 声明之前。这不需要封装在 @supports 中,因为旧版浏览器不会解析第二个声明,而是会使用第一个声明。
#stagger-list > .item {
animation-delay: calc(var(--sibling-index) * var(--stagger-time));
animation-delay: calc(sibling-index() * var(--stagger-time));
}