萬盛學電腦網

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

jQuery 實現元素閃爍提示:animate 顏色動畫、CSS3 替代方案與無障礙考量

原文方案分析(jQuery Color 動畫需額外插件)

// 原文代碼依賴 jQuery Color 插件才能 animate color
jQuery.fn.flash = function(color, duration) {
  var current = this.css('color');
  this.animate({ color: 'rgb(' + color + ')' }, duration / 2);
  this.animate({ color: current }, duration / 2);
};
$('#important').flash('255,0,0', 1000);

問題:jQuery 核心不支援顏色動畫,需額外引入 jquery-color 插件,否則 animate({color:...}) 無效果。

方案一:CSS3 Animation(零依賴、性能最佳、推薦)

<style>
@keyframes flash {
  0%, 100% { color: inherit; background-color: inherit; }
  50% { color: #fff; background-color: #e74c3c; }
}
.flash-once {
  animation: flash 1s ease-in-out 1;
}
.flash-loop {
  animation: flash 1s ease-in-out infinite;
}
/* 背景色閃爍版 */
@keyframes bg-flash {
  0%, 100% { background-color: inherit; }
  50% { background-color: #ffe0e0; }
}
.bg-flash { animation: bg-flash 1s ease-in-out 3; }
</style>

// JS 觸發
function flashElement($el, options) {
  var opts = $.extend({ count: 3, duration: 1000, type: 'bg' }, options);
  var cls = opts.type === 'color' ? 'flash-once' : 'bg-flash';
  // 動態設置動畫次數與時長
  $el.css({
    'animation-name': cls.replace('-once', '').replace('-loop', ''),
    'animation-duration': opts.duration + 'ms',
    'animation-iteration-count': opts.count,
    'animation-fill-mode': 'forwards'
  }).one('animationend', function() {
    $(this).css('animation', ''); // 清理內聯樣式
  });
}

// 使用
flashElement($('#warning'), { count: 3, duration: 800, type: 'bg' });

方案二:jQuery 隱藏/顯示切換(無顏色動畫、兼容性最好)

$.fn.flash = function(times, speed) {
  var $el = this;
  var count = 0;
  var max = times * 2; // 顯示+隱藏 = 1 次閃爍
  
  function toggle() {
    if (count >= max) {
      $el.show(); // 確保最終可見
      return;
    }
    $el[count % 2 === 0 ? 'fadeOut' : 'fadeIn'](speed, toggle);
    count++;
  }
  toggle();
  return this;
};

// 使用:閃爍 3 次,每次 200ms
$('#alert').flash(3, 200);

方案三:原生 CSS + class 切換(現代最佳)

<style>
@keyframes attention {
  0% { box-shadow: 0 0 0 0 rgba(231, 76, 60, 0.7); }
  70% { box-shadow: 0 0 0 10px rgba(231, 76, 60, 0); }
  100% { box-shadow: 0 0 0 0 rgba(231, 76, 60, 0); }
}
.attention-pulse {
  animation: attention 1.5s ease-out 3;
}
</style>

// JS
function pulse($el, times) {
  $el.addClass('attention-pulse')
     .one('animationend', function() { $(this).removeClass('attention-pulse'); });
}
pulse($('#saveBtn'), 3);

無障礙考量(WCAG 2.1)

  • 不要僅用顏色/閃爍傳達信息:需配合文字、圖標、aria-live 播報
  • 提供關閉/暫停控制:自動播放超過 5 秒的動畫必須可暫停
  • 避免高頻閃爍:3Hz 以上可能誘發光敏性癲癇(WCAG 2.3.1)
  • 尊重 prefers-reduced-motion:
    @media (prefers-reduced-motion: reduce) {
      .flash-once, .bg-flash, .attention-pulse { animation: none !important; }
    }

完整可運行示例

<!DOCTYPE html>
<html><head><meta charset="utf-8"><style>
/* CSS3 方案樣式 */
@keyframes bgFlash { 0%,100%{background:inherit} 50%{background:#ffe0e0} }
.bg-flash { animation: bgFlash 800ms ease-in-out; }
@keyframes pulse { 0%{box-shadow:0 0 0 0 rgba(231,76,60,.7)} 70%{box-shadow:0 0 0 10px rgba(231,76,60,0)} 100%{box-shadow:0 0 0 0 rgba(231,76,60,0)} }
.pulse { animation: pulse 1.5s ease-out; }

/* 減弱動畫 */
@media (prefers-reduced-motion: reduce) { .bg-flash, .pulse { animation: none !important; } }

.demo { padding:20px; margin:10px; border:1px solid #ddd; display:inline-block; }
</style></head><body>
<div class="demo bg-flash" id="d1">背景閃爍 (CSS 動畫)</div>
<div class="demo pulse" id="d2">脈衝邊框 (CSS 動畫)</div>
<div class="demo" id="d3">jQuery fadeIn/Out 閃爍</div>
<button onclick="flashCSS('#d1', 3)">觸發背景閃爍 3次</button>
<button onclick="pulseCSS('#d2', 2)">觸發脈衝 2次</button>
<button onclick="flashJQ('#d3', 3, 200)">觸發 jQuery 閃爍</button>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
function flashCSS(sel, times) { $(sel).css('animation-iteration-count', times).addClass('bg-flash').one('animationend', function(){ $(this).removeClass('bg-flash').css('animation',''); }); }
function pulseCSS(sel, times) { $(sel).css('animation-iteration-count', times).addClass('pulse').one('animationend', function(){ $(this).removeClass('pulse').css('animation',''); }); }
function flashJQ(sel, times, speed) { var $el=$(sel), c=0, max=times*2; (function t(){ if(c>=max) return $el.show(); $el[c++%2?'fadeOut':'fadeIn'](speed, t); })(); }
</script>
</body></html>

總結建議

  1. 首選 CSS3 Animation + class 切換:GPU 加速、無 JS 計算開銷、可暫停/逆向、尊重 prefers-reduced-motion。
  2. 簡單閃爍:fadeIn/fadeOut 遞歸切換,無依賴、兼容性極佳。
  3. 避免:jQuery animate({color})(需額外插件)、setInterval 手動修改樣式(幀率不可控、易卡頓)。
  4. 語義化:錯誤提示用 aria-live="assertive",裝飾性閃爍用 aria-hidden="true"。
copyright © 萬盛學電腦網 all rights reserved