萬盛學電腦網

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

CSS @keyframes 動畫關鍵幀語法詳解:from/to/百分比完整指南

前言

@keyframes 是 CSS 動畫的核心,定義動畫關鍵幀樣式。本文詳細說明語法結構、from/to 與百分比寫法、多關鍵幀排序、配合 animation 屬性使用的完整範例。

一、基本語法結構

@keyframes 動畫名稱 {
  from { /* 0% */ 屬性: 值; }
  百分比 { 屬性: 值; }
  to { /* 100% */ 屬性: 值; }
}

二、關鍵幀寫法對比

1. from / to(等同 0% / 100%)

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

2. 百分比關鍵幀(可定義中間狀態)

@keyframes bounce {
  0%   { transform: translateY(0); }
  50%  { transform: translateY(-100px); animation-timing-function: ease-out; }
  100% { transform: translateY(0); animation-timing-function: ease-in; }
}

3. 多屬性同時變化

@keyframes complex {
  0%   { opacity: 0; transform: scale(0.5) rotate(-180deg); background: red; }
  50%  { opacity: 1; transform: scale(1.2) rotate(0); background: yellow; }
  100% { opacity: 1; transform: scale(1) rotate(0); background: green; }
}

三、關鍵幀排序規則

  • 瀏覽器按百分比數值排序執行,非書寫順序。
  • 重複百分比:最後定義者勝出。
  • from 必為 0%,to 必為 100%,不可寫成其他值。

四、套用動畫:animation 屬性

.box {
  animation: fadeIn 1s ease-out 0s 1 normal forwards running;
}
/* 縮寫順序:name duration timing-function delay iteration-count direction fill-mode play-state */

常用子屬性

  • animation-name:對應 @keyframes 名稱
  • animation-duration:持續時間(秒/毫秒)
  • animation-timing-function:ease、linear、ease-in、ease-out、cubic-bezier()、steps()
  • animation-delay:延遲啟動
  • animation-iteration-count:次數或 infinite
  • animation-direction:normal、reverse、alternate、alternate-reverse
  • animation-fill-mode:none、forwards(保留末幀)、backwards、both
  • animation-play-state:running、paused

五、完整實戰範例:脈衝呼吸燈

@keyframes pulse {
  0%   { box-shadow: 0 0 0 0 rgba(255,0,0,0.7); }
  70%  { box-shadow: 0 0 0 20px rgba(255,0,0,0); }
  100% { box-shadow: 0 0 0 0 rgba(255,0,0,0); }
}

.pulse-btn {
  width: 60px; height: 60px; border-radius: 50%;
  background: #ff3b30;
  animation: pulse 2s infinite;
}

六、效能與最佳實踐

  1. 優先動畫 transform/opacity:僅觸發合成,不觸發重排重繪,效能最佳。
  2. 使用 will-change:提前告知瀏覽器將變化的屬性(will-change: transform, opacity;),但勿濫用。
  3. 避免動畫 layout 屬性:width/height/margin/padding/top/left 會觸發重排。
  4. 關鍵幀數量適中:過多關鍵幀增加瀏覽器計算負擔。
  5. 減少同時動畫元素數量:超過 10-20 個同時動畫可能掉幀。

結語

@keyframes 讓 CSS 擁有時間軸控制能力。熟練掌握百分比關鍵幀、多屬性協同、timing-function 節奏控制,配合 animation 縮寫與效能原則,即可創作流暢、高效能的網頁動畫。

copyright © 萬盛學電腦網 all rights reserved