首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

CSS3 動畫完整指南:@keyframes 規則與 animation 屬性詳解

     編輯:Java 相關知識

CSS3 動畫核心概念

CSS3 動畫讓元素在不使用 JavaScript、GIF 或 Flash 的情況下,平滑地從一種樣式過渡到另一種。核心由兩部分組成:

  1. @keyframes 規則:定義動畫關鍵幀樣式
  2. animation 屬性:將關鍵幀綁定到元素,控制播放行為

@keyframes 規則語法

@keyframes 動畫名稱 {
    0%   { CSS 屬性: 值; }  /* 等同 from */
    25%  { CSS 屬性: 值; }
    50%  { CSS 屬性: 值; }
    100% { CSS 屬性: 值; }  /* 等同 to */
}
  • 百分比表示動畫進度(0% 開始,100% 結束)
  • 可用 from/to 替代 0%/100%
  • 建議始終定義 0% 和 100% 以獲得最佳瀏覽器相容性

瀏覽器相容性與前綴

瀏覽器@keyframesanimation備註
IE 10+標準標準IE 9 以下不支援
Firefox標準標準早期需 -moz-
Chrome / Safari-webkit--webkit-新版支援標準
Opera標準標準早期需 -o-

最佳實踐:同時寫標準與 -webkit- 版本,其他前綴視專案需求補充。

完整前綴寫法範例

@keyframes slideColor {
    0%   { background: red; left: 0; top: 0; }
    25%  { background: yellow; left: 200px; top: 0; }
    50%  { background: blue; left: 200px; top: 200px; }
    75%  { background: green; left: 0; top: 200px; }
    100% { background: red; left: 0; top: 0; }
}

@-webkit-keyframes slideColor { /* 同內容 */ }
@-moz-keyframes slideColor { /* 同內容 */ }
@-o-keyframes slideColor { /* 同內容 */ }

animation 八大屬性詳解

屬性說明預設值常用值
animation-name關鍵幀名稱noneslideColor
animation-duration一個週期耗時0(動畫不執行)5s、2000ms
animation-timing-function速度曲線easelinear、ease-in、ease-out、cubic-bezier(...)
animation-delay延遲開始02s
animation-iteration-count播放次數1infinite、3
animation-direction方向normalreverse、alternate、alternate-reverse
animation-play-state播放狀態runningpaused
animation-fill-mode動畫前後狀態noneforwards、backwards、both

綁定動畫到元素

分屬性寫法

div {
    animation-name: slideColor;
    animation-duration: 5s;
    animation-timing-function: linear;
    animation-delay: 2s;
    animation-iteration-count: infinite;
    animation-direction: alternate;
    animation-play-state: running;
    /* -webkit- 前綴同寫一遍 */
}

簡寫寫法(推薦)

div {
    animation: slideColor 5s linear 2s infinite alternate;
    -webkit-animation: slideColor 5s linear 2s infinite alternate;
}

順序:name duration timing-function delay iteration-count direction fill-mode play-state(fill-mode 和 play-state 不包含在簡寫中,需單獨設定)。

進階技巧

多組動畫同時套用

div {
    animation: 
        move 3s ease-in-out infinite alternate,
        fade 2s linear infinite;
}

動畫事件(JavaScript 互動)

element.addEventListener('animationstart', e => console.log('開始'));
element.addEventListener('animationend', e => console.log('結束'));
element.addEventListener('animationiteration', e => console.log('重複'));

fill-mode 實用場景

  • forwards:動畫結束保持最後一幀(如載入完成保持勾勾)
  • backwards:延遲期間套用第一幀(避免閃爍)
  • both:兩者兼具

效能建議

  1. 優先動畫 transform、opacity(僅觸發合成,不觸發佈局/繪製)
  2. 避免動畫 width/height/left/top(觸發重排)
  3. 使用 will-change: transform, opacity; 提前告知瀏覽器優化
  4. 複雜動畫考慮 requestAnimationFrame + Canvas/WebGL

總結

CSS3 動畫以 @keyframes 定義關鍵幀,animation 控制播放,是現代 Web 動畫的基石。掌握八大屬性與簡寫語法,配合 transform/opacity 高效能屬性,即可創建流暢、無 JS 依賴的豐富互動體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved