萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS Animation 動畫完整指南:@keyframes 關鍵幀、動畫屬性、事件控制與效能優化

核心概念:關鍵幀

@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關鍵幀名稱noneslide-in
animation-duration單次動畫時長0s2s, 200ms
animation-timing-function速度曲線easelinear, ease-in-out, cubic-bezier(.4,0,.2,1), steps(4,end)
animation-delay延遲開始0s1s, -500ms (負值=從中間開始)
animation-iteration-count播放次數13, infinite
animation-direction播放方向normalreverse, alternate, alternate-reverse
animation-fill-mode動畫前後狀態noneforwards (保留末幀), backwards (套用首幀), both
animation-play-state播放狀態runningpaused (配合 :hover 暫停)

速記屬性 animation

.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;
}

Animation vs Transition 核心差異

特性TransitionAnimation
觸發方式需狀態變化(:hover、class 切換、JS)自動播放,無需觸發
關鍵幀控制僅首尾兩態多關鍵幀,精細控制
循環播放不支援支援 infinite
方向控制無支援 alternate 等
暫停/繼續困難animation-play-state
JS 事件transitionendanimationstart, animationend, animationiteration

JS 事件控制範例

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';

效能優化黃金法則

  1. 只動 transform / opacity:觸發合成器層,GPU 加速,不觸發 Layout/Repaint。
  2. 避免動畫 width/height/top/left/margin/padding:觸發 Layout → Paint → Composite,嚴重掉幀。
  3. 使用 will-change 提示瀏覽器:will-change: transform, opacity;(用畢即刪,避免記憶體洩漏)。
  4. 減少同時動畫元素數量,尤其手機端。
  5. 優先用 CSS 動畫而非 JS 迴圈:主執行緒阻塞不影響 CSS 動畫。

減少動畫偏好

@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 進階主題,請關注本站動畫專欄。

copyright © 萬盛學電腦網 all rights reserved