萬盛學電腦網

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

JavaScript 實作文字大小顏色動態變化特效

透過 `setInterval` 定時修改元素 `fontSize` 與 `color`,可製作閃爍、呼吸、彩虹等視覺特效。本文提供基礎版、可配置版與現代 CSS 動畫替代方案。

基礎版:原始邏輯重構

<div id="dynamic-text" style="font-size: 20px;">
  你好,這是一段會變大小、變顏色的文字特效
</div>

<script>
const el = document.getElementById('dynamic-text');
let size = 20;
let direction = 1; // 1: 變大, -1: 變小
const MIN_SIZE = 20, MAX_SIZE = 60;
const SPEED = 200; // ms

function getRandomColor() {
  // 產生隨機十六進位顏色 #RRGGBB
  return '#' + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0');
}

function animate() {
  // 更新大小
  size += direction;
  if (size >= MAX_SIZE) direction = -1;
  if (size <= MIN_SIZE) direction = 1;
  el.style.fontSize = size + 'px';
  
  // 更新顏色
  el.style.color = getRandomColor();
}

setInterval(animate, SPEED);
</script>

可配置版:支援多元素、暫停/繼續、銷毀

class TextAnimator {
  constructor(selector, options = {}) {
    this.elements = [...document.querySelectorAll(selector)];
    this.options = {
      minSize: 16,
      maxSize: 48,
      step: 1,
      interval: 200,
      colorMode: 'random', // 'random' | 'rainbow' | 'fixed' | function
      fixedColor: '#ff0000',
      ...options
    };
    this.timer = null;
    this.hue = 0;
  }
  
  start() {
    if (this.timer) return;
    this.timer = setInterval(() => this.tick(), this.options.interval);
  }
  
  stop() {
    clearInterval(this.timer);
    this.timer = null;
  }
  
  destroy() {
    this.stop();
    this.elements.forEach(el => {
      el.style.fontSize = '';
      el.style.color = '';
    });
  }
  
  tick() {
    this.elements.forEach(el => {
      // 字體大小來回縮放
      const currentSize = parseFloat(el.style.fontSize) || this.options.minSize;
      let newSize = currentSize + this.options.step * (this.direction || 1);
      if (newSize >= this.options.maxSize) { newSize = this.options.maxSize; this.direction = -1; }
      if (newSize <= this.options.minSize) { newSize = this.options.minSize; this.direction = 1; }
      el.style.fontSize = newSize + 'px';
      
      // 顏色模式
      switch (this.options.colorMode) {
        case 'random':
          el.style.color = '#' + Math.floor(Math.random()*0xffffff).toString(16).padStart(6,'0');
          break;
        case 'rainbow':
          el.style.color = `hsl(${this.hue}, 100%, 50%)`;
          this.hue = (this.hue + 10) % 360;
          break;
        case 'fixed':
          el.style.color = this.options.fixedColor;
          break;
        default:
          if (typeof this.options.colorMode === 'function') {
            el.style.color = this.options.colorMode(el);
          }
      }
    });
  }
}

// 使用
const animator = new TextAnimator('#dynamic-text', {
  minSize: 20, maxSize: 60, interval: 200, colorMode: 'rainbow'
});
animator.start();

// 頁面隱藏時暫停,節省資源
document.addEventListener('visibilitychange', () => {
  if (document.hidden) animator.stop();
  else animator.start();
});

現代最佳實踐:CSS Animation(零 JS、效能最佳)

@keyframes font-size-pulse {
  0%, 100% { font-size: 20px; }
  50%      { font-size: 60px; }
}
@keyframes color-rainbow {
  0%   { color: hsl(0,   100%, 50%); }
  16%  { color: hsl(60,  100%, 50%); }
  33%  { color: hsl(120, 100%, 50%); }
  50%  { color: hsl(180, 100%, 50%); }
  66%  { color: hsl(240, 100%, 50%); }
  83%  { color: hsl(300, 100%, 50%); }
  100% { color: hsl(360, 100%, 50%); }
}

.dynamic-text {
  animation: 
    font-size-pulse 4s ease-in-out infinite,
    color-rainbow 8s linear infinite;
}

/* 尊重使用者偏好減少動畫 */
@media (prefers-reduced-motion: reduce) {
  .dynamic-text { animation: none; }
}

**優勢:** 由瀏覽器合成器執行(不佔主執行緒)、60fps 流暢、可被 `prefers-reduced-motion` 停用、無 JS 依賴。

無障礙與體驗建議

  • **避免**在大量文字、長篇閱讀內容使用此類特效,嚴重干擾閱讀。
  • 僅用於**裝飾性標題、行銷横幅、載入狀態**等非核心內容。
  • 提供**暫停/關閉按鈕**,或自動在 `prefers-reduced-motion` 停用。
  • 確保對比度符合 WCAG AA(動畫過程中亦需維持)。
  • 使用 `will-change: font-size, color` 提示瀏覽器最佳化(謹慎使用)。

效能比較

方案主執行緒佔用幀率穩定度記憶體可維護性
JS setInterval高(每幀觸發 JS、佈局、繪製)易掉幀低中(邏輯分散)
JS requestAnimationFrame中較好低中
CSS Animation極低(合成器執行)最佳極低高(宣告式)

**結論:** 能用 CSS Animation 解決的視覺特效,**絕不**用 JS 實作。保留 JS 版本僅供學習邏輯或極特殊動態需求(如根據資料即時計算顏色)。

copyright © 萬盛學電腦網 all rights reserved