核心實現:關鍵幀動畫
@keyframes blink {
0% { opacity: 0; }
50% { opacity: 1; }
100% { opacity: 0; }
}
/* 應用動畫 */
.blink-element {
animation: blink 1s infinite ease-in-out;
}
關鍵屬性詳解
| 屬性 | 值 | 說明 |
| animation-name | blink | 關鍵幀名稱 |
| animation-duration | 1s | 一個週期時長 |
| animation-iteration-count | infinite | 無限循環,或具體次數 |
| animation-timing-function | ease-in-out | 緩動函數:linear、ease、cubic-bezier() |
| animation-direction | alternate | 交替方向播放 (正反循環) |
| animation-fill-mode | forwards | 結束狀態保持 |
| animation-delay | 0.5s | 延遲啟動 |
| animation-play-state | running/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; }
性能與最佳實踐
- 優先使用 transform/opacity:僅觸發合成,不觸發重排重繪
- will-change 提示:
will-change: opacity, transform; 促進 GPU 層創建
- 減少動畫元素數量:大量閃爍影響性能,考慮 Canvas/WebGL
- 尊重用戶偏好:
@media (prefers-reduced-motion: reduce) { .blink { animation: none; } }
- 語義化類名:
.loading-pulse、.error-flash、.success-blink
瀏覽器兼容性
- 現代瀏覽器全支持 (含 IE10+)
- 舊 WebKit 需前綴
-webkit-animation、-webkit-keyframes
- Autoprefixer 自動處理前綴