交錯動畫可提供有趣的效果,讓多個排序元素依序顯示動畫,每個元素之間會稍微延遲,而不是一次顯示所有動畫。這項技術常用於清單、圖庫或導覽選單,可引導使用者視線,並為互動增添精緻、有節奏感的感覺。
使用 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 自訂屬性。MANDATORY: wrap this in a CSS.supports('animation-delay: calc(sibling-index() * 0.1s)') test to avoid running unneeded 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));
}