CSS3 Animation 由 @keyframes 定義關鍵幀序列,animation 屬性調用並控制播放行為。區別於 Transition (需事件觸發、只有開始/結束),Animation 可定義多個中間狀態,自動播放、循環、反向。
@keyframes <animation-name> {
from { /* 0% */ property: value; }
{ property: value; }
to { /* 100% */ property: value; }
}
/* 百分比寫法 (推薦,支援更多關鍵幀) */
@keyframes slide {
0% { left: 0; background: red; }
25% { left: 100px; background: orange; }
50% { left: 200px; background: yellow; }
75% { left: 100px; background: green; }
100% { left: 0; background: blue; }
}
注意:百分比值**必須帶 % 號**,否則無效。幀順序不影響結果,瀏覽器按百分比排序。
| 屬性 | 說明 | 示例值 |
|---|---|---|
animation-name | 關鍵幀名稱 | slide |
animation-duration | 單次動畫時長 | 2s, 2000ms |
animation-timing-function | 速度曲線 | ease, linear, cubic-bezier(.4,0,.2,1) |
animation-delay | 延遲啟動 | 1s |
animation-iteration-count | 循環次數 | 3, infinite |
animation-direction | 播放方向 | normal, reverse, alternate, alternate-reverse |
animation-fill-mode | 動畫前後狀態 | none, forwards, backwards, both |
animation-play-state | 播放狀態控制 | running, paused |
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
/* 實例 */
.demo {
animation: slide 3s ease-in-out 1s infinite alternate both;
}
@keyframes bounce {
0%, 100% { transform: translateY(0); animation-timing-function: ease-out; }
50% { transform: translateY(-100px); animation-timing-function: ease-in; }
}
.ball {
width: 50px; height: 50px; border-radius: 50%; background: #e74c3c;
animation: bounce 1s infinite;
}
動畫期間,關鍵幀樣式**覆蓋**元素原有樣式 (含內聯 style);動畫結束後,受 fill-mode 控制:
none (默認):恢復原樣式forwards:保留 100% 關鍵幀樣式backwards:延遲期間套用 0% 關鍵幀樣式both:同時生效-webkit-animation, @-webkit-keyframeswill-change: transform, opacity 提示瀏覽器預創建合成層transform/opacity 動畫 (GPU 加速),避免 left/top/width/height 觸發佈局重排const el = document.querySelector('.ball');
el.addEventListener('animationstart', () => console.log('開始'));
el.addEventListener('animationiteration', () => console.log('循環'));
el.addEventListener('animationend', () => console.log('結束'));
// 動態控制
el.style.animationPlayState = 'paused'; // 暫停
el.style.animationPlayState = 'running'; // 繼續