萬盛學電腦網

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

CSS Animation 動畫完整指南:@keyframes 關鍵幀定義與 animation 七大子屬性控制播放行為

@keyframes 關鍵幀語法

@keyframes slide-color {
  0%   { margin-left: 100px; background: green;  }
  40%  { margin-left: 150px; background: orange; }
  60%  { margin-left: 75px;  background: blue;   }
  100% { margin-left: 100px; background: red;    }
}

/* 等價 from/to */
@keyframes slide-color {
  from { margin-left: 100px; background: green; }
  40%  { margin-left: 150px; background: orange; }
  60%  { margin-left: 75px;  background: blue;   }
  to   { margin-left: 100px; background: red;    }
}

規則:百分比必須帶 %,from=0%,to=100%,順序不限,瀏覽器自動排序。

animation 七大子屬性

屬性說明常用值
animation-name關鍵幀名稱slide-color / none
animation-duration一週期時長2s、2000ms
animation-timing-function速度曲線ease、linear、ease-in-out、cubic-bezier()
animation-delay延遲啟動1s、-500ms(負值立即進入進行中)
animation-iteration-count播放次數3、infinite
animation-direction播放方向normal、reverse、alternate、alternate-reverse
animation-fill-mode動畫前後狀態none、forwards、backwards、both

綜合簡寫

.demo {
  width: 50px; height: 50px;
  background: blue;
  animation: slide-color 10s ease-in-out 2s infinite alternate both;
  /* name duration timing delay count direction fill-mode */
}

關鍵行為細節

  • 層疊覆蓋:動畫期間,關鍵幀樣式**覆蓋**元素原有樣式;動畫結束後,依 fill-mode 決定保留或還原。
  • 不觸發佈局重排:優先動畫 transform、opacity、filter(合成器線程處理,60fps 流暢)。
  • will-change:提示瀏覽器預先優化 will-change: transform, opacity;。
  • prefers-reduced-motion:尊重用戶減少動畫偏好 @media (prefers-reduced-motion: reduce) { * { animation: none !important; } }。

瀏覽器支援

現代瀏覽器全支援無前綴。IE10/11 需 -ms- 前綴(Autoprefixer 自動處理)。

copyright © 萬盛學電腦網 all rights reserved