CSS3 動畫讓元素在不使用 JavaScript、GIF 或 Flash 的情況下,平滑地從一種樣式過渡到另一種。核心由兩部分組成:
@keyframes 動畫名稱 {
0% { CSS 屬性: 值; } /* 等同 from */
25% { CSS 屬性: 值; }
50% { CSS 屬性: 值; }
100% { CSS 屬性: 值; } /* 等同 to */
}
from/to 替代 0%/100%| 瀏覽器 | @keyframes | animation | 備註 |
|---|---|---|---|
| IE 10+ | 標準 | 標準 | IE 9 以下不支援 |
| Firefox | 標準 | 標準 | 早期需 -moz- |
| Chrome / Safari | -webkit- | -webkit- | 新版支援標準 |
| Opera | 標準 | 標準 | 早期需 -o- |
最佳實踐:同時寫標準與 -webkit- 版本,其他前綴視專案需求補充。
@keyframes slideColor {
0% { background: red; left: 0; top: 0; }
25% { background: yellow; left: 200px; top: 0; }
50% { background: blue; left: 200px; top: 200px; }
75% { background: green; left: 0; top: 200px; }
100% { background: red; left: 0; top: 0; }
}
@-webkit-keyframes slideColor { /* 同內容 */ }
@-moz-keyframes slideColor { /* 同內容 */ }
@-o-keyframes slideColor { /* 同內容 */ }
| 屬性 | 說明 | 預設值 | 常用值 |
|---|---|---|---|
| animation-name | 關鍵幀名稱 | none | slideColor |
| animation-duration | 一個週期耗時 | 0(動畫不執行) | 5s、2000ms |
| animation-timing-function | 速度曲線 | ease | linear、ease-in、ease-out、cubic-bezier(...) |
| animation-delay | 延遲開始 | 0 | 2s |
| animation-iteration-count | 播放次數 | 1 | infinite、3 |
| animation-direction | 方向 | normal | reverse、alternate、alternate-reverse |
| animation-play-state | 播放狀態 | running | paused |
| animation-fill-mode | 動畫前後狀態 | none | forwards、backwards、both |
div {
animation-name: slideColor;
animation-duration: 5s;
animation-timing-function: linear;
animation-delay: 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-play-state: running;
/* -webkit- 前綴同寫一遍 */
}
div {
animation: slideColor 5s linear 2s infinite alternate;
-webkit-animation: slideColor 5s linear 2s infinite alternate;
}
順序:name duration timing-function delay iteration-count direction fill-mode play-state(fill-mode 和 play-state 不包含在簡寫中,需單獨設定)。
div {
animation:
move 3s ease-in-out infinite alternate,
fade 2s linear infinite;
}
element.addEventListener('animationstart', e => console.log('開始'));
element.addEventListener('animationend', e => console.log('結束'));
element.addEventListener('animationiteration', e => console.log('重複'));
forwards:動畫結束保持最後一幀(如載入完成保持勾勾)backwards:延遲期間套用第一幀(避免閃爍)both:兩者兼具transform、opacity(僅觸發合成,不觸發佈局/繪製)width/height/left/top(觸發重排)will-change: transform, opacity; 提前告知瀏覽器優化requestAnimationFrame + Canvas/WebGLCSS3 動畫以 @keyframes 定義關鍵幀,animation 控制播放,是現代 Web 動畫的基石。掌握八大屬性與簡寫語法,配合 transform/opacity 高效能屬性,即可創建流暢、無 JS 依賴的豐富互動體驗。