CSS Animation 讓聲明式動畫成為可能,無需 JavaScript 即可實現複雜序列動畫。本文系統梳理 8 大子屬性語法、3 大事件接口,並提供可直接運行的完整示例。
| 屬性 | 作用 | 關鍵值 |
|---|---|---|
animation-name | 綁定 @keyframes 名稱 | none | custom-name |
animation-duration | 單次動畫時長 | <time> (s/ms),默認 0 |
animation-timing-function | 緩動曲線 | ease/linear/ease-in/out/in-out/cubic-bezier() |
animation-delay | 延遲啟動 | <time>,默認 0 |
animation-iteration-count | 循環次數 | <number> | infinite,默認 1 |
animation-direction | 播放方向 | normal | alternate | reverse | alternate-reverse |
animation-fill-mode | 執行前後狀態 | none | forwards | backwards | both |
animation-play-state | 播放狀態控制 | running | paused |
/* 百分比形式(推薦,支援中間態) */
@keyframes color-change {
0% { background: red; }
25% { background: green; }
50% { background: blue; }
100% { background: red; }
}
/* from/to 形式(簡單兩態) */
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
.demo {
animation: color-change 1s linear 0s 3 alternate both;
/* name duration timing delay count direction fill-mode */
}
三大原生事件(需廠商前綴兼容):
animationstart / webkitAnimationStart:動畫開始animationiteration / webkitAnimationIteration:每次循環結束(含首次)animationend / webkitAnimationEnd:動畫完全結束事件對象 包含 animationName、elapsedTime 等屬性,可識別具體動畫與已運行時間。
<style>
@keyframes test {
0% { background: red; }
25% { background: green; }
50% { background: blue; }
100% { background: red; }
}
</style>
<script>
document.addEventListener('DOMContentLoaded', () => {
const html = document.documentElement;
const log = (e) => console.log(e.type, e.animationName, e.elapsedTime);
['animationstart','webkitAnimationStart'].forEach(evt =>
html.addEventListener(evt, log));
['animationiteration','webkitAnimationIteration'].forEach(evt =>
html.addEventListener(evt, log));
['animationend','webkitAnimationEnd'].forEach(evt =>
html.addEventListener(evt, log));
// 觸發動畫:3次循環,每次1秒
html.style.animation = 'test 1s linear 0s 3';
});
</script>

transform、opacity、filter 觸發合成器層,避免佈局抖動will-change: transform, opacity@media (prefers-reduced-motion: reduce) 關閉非必要動畫CSS Animation 讓動畫脫離 JS 主線程,在合成器線程高效運行。掌握屬性組合與事件控制,即可構建流暢、可維護、可交互的動畫體驗。