@keyframes 定義動畫關鍵時間點的樣式狀態,瀏覽器自動插值產生中間幀。語法:
@keyframes slide-in {
0% { transform: translateX(-100%); opacity: 0; }
50% { transform: translateX(10px); opacity: 0.8; }
100% { transform: translateX(0); opacity: 1; }
}
/* 等價 from/to 寫法 */
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
0% 不能寫 0)。from = 0%,to = 100%。| 屬性 | 說明 | 預設值 | 常用值 |
|---|---|---|---|
animation-name | 關鍵幀名稱 | none | slide-in |
animation-duration | 單次動畫時長 | 0s | 2s, 200ms |
animation-timing-function | 速度曲線 | ease | linear, ease-in-out, cubic-bezier(.4,0,.2,1), steps(4,end) |
animation-delay | 延遲開始 | 0s | 1s, -500ms (負值=從中間開始) |
animation-iteration-count | 播放次數 | 1 | 3, infinite |
animation-direction | 播放方向 | normal | reverse, alternate, alternate-reverse |
animation-fill-mode | 動畫前後狀態 | none | forwards (保留末幀), backwards (套用首幀), both |
animation-play-state | 播放狀態 | running | paused (配合 :hover 暫停) |
.demo {
/* name duration timing-function delay iteration-count direction fill-mode play-state */
animation: slide-in 2s ease-in-out 0.5s 3 alternate both running;
}
順序建議遵循上表,animation-name 必須在第一位。
@keyframes bounce {
0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-30px); }
60% { transform: translateY(-15px); }
}
.loader {
width: 40px; height: 40px;
border-radius: 50%;
background: #007bff;
animation: bounce 1.5s ease-in-out infinite;
}
| 特性 | Transition | Animation |
|---|---|---|
| 觸發方式 | 需狀態變化(:hover、class 切換、JS) | 自動播放,無需觸發 |
| 關鍵幀控制 | 僅首尾兩態 | 多關鍵幀,精細控制 |
| 循環播放 | 不支援 | 支援 infinite |
| 方向控制 | 無 | 支援 alternate 等 |
| 暫停/繼續 | 困難 | animation-play-state |
| JS 事件 | transitionend | animationstart, animationend, animationiteration |
const el = document.querySelector('.box');
el.addEventListener('animationend', (e) => {
if (e.animationName === 'slide-in') {
el.classList.add('loaded');
}
});
// 動態修改動畫
el.style.animationDuration = '3s';
el.style.animationPlayState = 'paused';
will-change: transform, opacity;(用畢即刪,避免記憶體洩漏)。@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
尊重用戶系統設定,提升無障礙體驗。
掌握 @keyframes 與 animation 全屬性,讓網頁動起來既流暢又可控。更多 Web Animation API、Scroll-driven Animations 進階主題,請關注本站動畫專欄。