萬盛學電腦網

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

CSS3 Animation 動畫屬性完整詳解:@keyframes 關鍵幀與動畫控制屬性

核心概念:關鍵幀

CSS3 Animation 由 @keyframes 定義關鍵幀序列,animation 屬性調用並控制播放行為。區別於 Transition (需事件觸發、只有開始/結束),Animation 可定義多個中間狀態,自動播放、循環、反向。

@keyframes 語法規範

@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 子屬性

屬性說明示例值
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:同時生效

瀏覽器前綴與現代最佳實踐

  • 現代瀏覽器 (Chrome 43+, Firefox 16+, Safari 9+, Edge 12+) **無需前綴**
  • 舊版 WebKit 需 -webkit-animation, @-webkit-keyframes
  • 構建工具 (PostCSS/Autoprefixer) 自動處理前綴
  • 性能優化:will-change: transform, opacity 提示瀏覽器預創建合成層
  • 優先使用 transform/opacity 動畫 (GPU 加速),避免 left/top/width/height 觸發佈局重排

JavaScript 事件控制

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'; // 繼續
copyright © 萬盛學電腦網 all rights reserved