萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

CSS3 實現元素閃爍動畫:@keyframes 與 animation 屬性完整指南

核心實現:關鍵幀動畫


@keyframes blink {
  0%   { opacity: 0; }
  50%  { opacity: 1; }
  100% { opacity: 0; }
}

/* 應用動畫 */
.blink-element {
  animation: blink 1s infinite ease-in-out;
}

關鍵屬性詳解

屬性值說明
animation-nameblink關鍵幀名稱
animation-duration1s一個週期時長
animation-iteration-countinfinite無限循環,或具體次數
animation-timing-functionease-in-out緩動函數:linear、ease、cubic-bezier()
animation-directionalternate交替方向播放 (正反循環)
animation-fill-modeforwards結束狀態保持
animation-delay0.5s延遲啟動
animation-play-staterunning/paused動態控制播放/暫停

簡寫屬性順序


/* 順序:name duration timing-function delay iteration-count direction fill-mode play-state */
animation: blink 1s ease-in-out 0s infinite alternate forwards running;

jQuery 動態控制 (兼容舊項目)


// 添加動畫
$('#element').css({
  '-webkit-animation': 'blink 1s infinite ease-in-out',
  'animation': 'blink 1s infinite ease-in-out'
});

// 移除動畫
$('#element').css('animation', 'none');

// 切換播放狀態
$('#element').css('animation-play-state', 'paused');

進階閃爍變體

背景色閃爍 (不改變佈局)


@keyframes bg-blink {
  0%, 100% { background-color: transparent; }
  50% { background-color: #ffeb3b; }
}
.warning { animation: bg-blink 0.5s infinite; }

邊框閃爍


@keyframes border-blink {
  0%, 100% { border-color: transparent; }
  50% { border-color: #f44336; }
}

縮放閃爍 (脈衝效果)


@keyframes pulse {
  0% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.05); opacity: 0.7; }
  100% { transform: scale(1); opacity: 1; }
}
.pulse { animation: pulse 2s infinite; }

性能與最佳實踐

  1. 優先使用 transform/opacity:僅觸發合成,不觸發重排重繪
  2. will-change 提示:will-change: opacity, transform; 促進 GPU 層創建
  3. 減少動畫元素數量:大量閃爍影響性能,考慮 Canvas/WebGL
  4. 尊重用戶偏好:@media (prefers-reduced-motion: reduce) { .blink { animation: none; } }
  5. 語義化類名:.loading-pulse、.error-flash、.success-blink

瀏覽器兼容性

  • 現代瀏覽器全支持 (含 IE10+)
  • 舊 WebKit 需前綴 -webkit-animation、-webkit-keyframes
  • Autoprefixer 自動處理前綴
copyright © 萬盛學電腦網 all rights reserved