萬盛學電腦網

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

jQuery 團購倒計時元件:多實例、可配置、無障礙完整實作

功能需求

  • 支援多個倒計時實例並存
  • 可配置:目標時間、是否顯示天數、語言、過期文案
  • 精確到秒,每秒更新
  • 過期後自動停止、顯示自訂文案
  • 無障礙:aria-live 播報剩餘時間

HTML 結構

<div class="countdown-container">
  <h2>含天數倒計時</h2>
  <div class="countdown" 
       data-end="2025-12-31T23:59:59+08:00" 
       data-show-days="true"
       data-locale="zh-TW"
       data-expired-text="活動已結束"
       aria-live="polite"></div>
  
  <div class="countdown" 
       data-end="2025-06-15T12:00:00+08:00" 
       data-show-days="false"
       aria-live="polite"></div>
</div>

核心邏輯:ES6 Class 封裝

class CountdownTimer {
  constructor(element, options = {}) {
    this.el = element;
    this.options = Object.assign({
      endTime: element.dataset.end,
      showDays: element.dataset.showDays !== "false",
      locale: element.dataset.locale || "zh-TW",
      expiredText: element.dataset.expiredText || "已過期",
      updateInterval: 1000
    }, options);
    
    this.timer = null;
    this.isExpired = false;
    this.lastAnnounced = "";
    
    this.init();
  }
  
  init() {
    // 驗證目標時間
    this.endTimestamp = Date.parse(this.options.endTime);
    if (isNaN(this.endTimestamp)) {
      console.error("無效的結束時間:", this.options.endTime);
      this.el.textContent = "時間格式錯誤";
      return;
    }
    
    // 立即執行一次
    this.tick();
    // 定時器
    this.timer = setInterval(() => this.tick(), this.options.updateInterval);
  }
  
  tick() {
    const now = Date.now();
    const diff = this.endTimestamp - now;
    
    if (diff <= 0) {
      this.expire();
      return;
    }
    
    const timeParts = this.calculateTimeParts(diff);
    const html = this.renderHTML(timeParts);
    this.el.innerHTML = html;
    
    // 無障礙播報(避免頻繁播報)
    const announceText = this.formatAnnounce(timeParts);
    if (announceText !== this.lastAnnounced) {
      this.el.setAttribute("aria-label", announceText);
      this.lastAnnounced = announceText;
    }
  }
  
  calculateTimeParts(diffMs) {
    const totalSeconds = Math.floor(diffMs / 1000);
    const days = Math.floor(totalSeconds / 86400);
    const hours = Math.floor((totalSeconds % 86400) / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;
    
    return { days, hours, minutes, seconds, totalSeconds };
  }
  
  renderHTML({ days, hours, minutes, seconds }) {
    const pad = (n) => String(n).padStart(2, "0");
    const unit = (value, label) => 
      `${value}${label}`;
    
    if (this.options.showDays) {
      return `剩餘時間:
        ${unit(days, this.getLabel("day"))}
        ${unit(pad(hours), this.getLabel("hour"))}
        ${unit(pad(minutes), this.getLabel("min"))}
        ${unit(pad(seconds), this.getLabel("sec"))}`;
    } else {
      // 不顯示天數:總小時數
      const totalHours = Math.floor((days * 24) + hours);
      return `剩餘時間:
        ${unit(pad(totalHours), this.getLabel("hour"))}
        ${unit(pad(minutes), this.getLabel("min"))}
        ${unit(pad(seconds), this.getLabel("sec"))}`;
    }
  }
  
  getLabel(unit) {
    const labels = {
      "zh-TW": { day: "天", hour: "時", min: "分", sec: "秒" },
      "zh-CN": { day: "天", hour: "时", min: "分", sec: "秒" },
      "en": { day: "d", hour: "h", min: "m", sec: "s" },
      "ja": { day: "日", hour: "時間", min: "分", sec: "秒" }
    };
    return (labels[this.options.locale] || labels["zh-TW"])[unit];
  }
  
  formatAnnounce({ days, hours, minutes, seconds }) {
    const parts = [];
    if (this.options.showDays && days) parts.push(`${days} ${this.getLabel("day")}`);
    if (hours) parts.push(`${hours} ${this.getLabel("hour")}`);
    if (minutes) parts.push(`${minutes} ${this.getLabel("min")}`);
    parts.push(`${seconds} ${this.getLabel("sec")}`);
    return `剩餘 ${parts.join(" ")}`;
  }
  
  expire() {
    if (this.isExpired) return;
    this.isExpired = true;
    clearInterval(this.timer);
    this.el.innerHTML = `${this.options.expiredText}`;
    this.el.setAttribute("aria-label", this.options.expiredText);
  }
  
  destroy() {
    clearInterval(this.timer);
    this.el.innerHTML = "";
    this.el.removeAttribute("aria-label");
  }
}

// 自動初始化所有 .countdown 元素
document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll(".countdown").forEach(el => {
    new CountdownTimer(el);
  });
});

CSS 樣式系統

.countdown {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font-family: 'SF Mono', 'Monospace', monospace;
  font-size: 1.125rem;
  color: #2c3e50;
}
.cd-prefix { font-weight: 500; color: #7f8c8d; }
.cd-unit { display: inline-flex; flex-direction: column; align-items: center; min-width: 2.5em; }
.cd-value { font-weight: 700; font-size: 1.25em; line-height: 1.2; }
.cd-label { font-size: 0.7em; color: #95a5a6; text-transform: uppercase; }
.cd-expired { color: #e74c3c; font-weight: 600; }

/* 響應式:小螢幕隱藏標籤 */
@media (max-width: 480px) {
  .cd-label { display: none; }
  .cd-unit { min-width: auto; padding: 0 4px; }
}

/* 動畫效果 */
@keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.05); } }
.cd-value.changed { animation: pulse 0.3s ease; }

數值變化動畫增強

renderHTML(timeParts) {
  // ... 產生 HTML 字串 ...
  // 為了數值變化動畫,需比較前後值
  // 簡化版:直接替換 innerHTML,配合 CSS animation
  // 進階版:逐字符比對,僅更新變化的 span
}

時區處理最佳實踐

🕐 時區關鍵點

  • 永遠使用 ISO 8601 含時區格式:2025-12-31T23:59:59+08:00
  • 避免 new Date("12/31/2025"):依賴瀏覽器本地時區解析,極不穩定
  • 伺服器端渲染時:輸出 UTC 時間 2025-12-31T15:59:59Z,前端自動轉換為用戶本地時間
  • 測試時區:Chrome DevTools → Sensors → Timezone 切換驗證

單元測試範例 (Jest)

describe("CountdownTimer", () => {
  beforeEach(() => {
    jest.useFakeTimers();
    document.body.innerHTML = '<div class="countdown" data-end="2099-01-01T00:00:00+08:00"></div>';
  });
  
  test("正確計算剩餘時間", () => {
    const el = document.querySelector(".countdown");
    new CountdownTimer(el);
    
    // 模擬時間前進 1 小時
    jest.advanceTimersByTime(3600 * 1000);
    
    expect(el.textContent).toContain("剩餘時間");
    expect(el.querySelector(".cd-value").textContent).toMatch(/\d+/);
  });
  
  test("過期顯示正確文案", () => {
    const el = document.querySelector(".countdown");
    const timer = new CountdownTimer(el, { endTime: "2020-01-01T00:00:00+08:00" });
    
    jest.advanceTimersByTime(1000);
    expect(el.textContent).toBe("已過期");
  });
});

總結

這個倒計時元件展示了現代前端元件開發的核心素養:資料驅動視圖、配置外部化、無障礙優先、時區正確處理、生命週期管理(init/tick/destroy)。配合 CSS 變數與 BEM 命名,可輕鬆主題化、擴展為「促銷倒計時」、「直播開播倒計時」、「考試截止倒計時」等多種業務場景。

copyright © 萬盛學電腦網 all rights reserved