aria-live 播報剩餘時間<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>
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);
});
});
.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
}
2025-12-31T23:59:59+08:00new Date("12/31/2025"):依賴瀏覽器本地時區解析,極不穩定2025-12-31T15:59:59Z,前端自動轉換為用戶本地時間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 命名,可輕鬆主題化、擴展為「促銷倒計時」、「直播開播倒計時」、「考試截止倒計時」等多種業務場景。