在網頁標題列 (<title>) 或頁面指定區域即時顯示日期時間,是提升資訊即時感的經典需求。HTML5 配合 JavaScript Date API 與 setInterval,可輕鬆實現秒級更新的動態時鐘。
Date 物件取得當前時間document.title 或 element.textContent)setInterval 每 1000ms 重複執行<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>載入中...</title>
<style>
body { font-family: 'Microsoft JhengHei', sans-serif; padding: 40px; text-align: center; }
.clock { font-size: 3rem; font-family: 'Consolas', 'Monospace'; color: #2c3e50; }
</style>
</head>
<body>
<h1>標題列即時時鐘</h1>
<div class="clock" id="pageClock">--:--:--</div>
<p>觀察瀏覽器分頁標題列時間同步更新</p>
<script>
(function() {
const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
const clockEl = document.getElementById('pageClock');
function updateClock() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
const week = weekDays[now.getDay()];
// 格式:2024/12/25 14:30:05 星期三
const timeStr = `${year}/${month}/${day} ${hours}:${minutes}:${seconds} ${week}`;
// 更新頁面顯示
clockEl.textContent = timeStr;
// 同步更新瀏覽器標題列
document.title = timeStr;
}
// 立即執行一次
updateClock();
// 每秒更新
const timerId = setInterval(updateClock, 1000);
// 頁面卸載清理 (良好習慣)
window.addEventListener('beforeunload', () => clearInterval(timerId));
// 頁面可見性優化:隱藏時暫停,顯示時恢復
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
clearInterval(timerId);
} else {
updateClock(); // 立即同步
// 重新啟動 (這裡簡化,實際需重新 setInterval)
}
});
})();
</script>
</body>
</html>
<span id="liveClock"></span>
<script>
const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
const target = document.getElementById('liveClock');
function renderTime() {
const d = new Date();
const fmt = (n) => String(n).padStart(2, '0');
const str = `${d.getFullYear()}年${fmt(d.getMonth()+1)}月${fmt(d.getDate())}日 ` +
`${fmt(d.getHours())}:${fmt(d.getMinutes())}:${fmt(d.getSeconds())} ` +
`${weekDays[d.getDay()]}`;
target.textContent = str;
}
renderTime();
setInterval(renderTime, 1000);
</script>
const formatter = new Intl.DateTimeFormat('zh-TW', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false, weekday: 'long'
});
function renderTime() {
target.textContent = formatter.format(new Date()).replace(/\//g, '/');
}
// 輸出範例:2024/12/25 下午 02:30:05 星期三
timeZone 選項顯示不同時區時間| 問題 | 原因 | 解決 |
|---|---|---|
| 秒數跳動不流暢 | setInterval 不精確、主執行緒阻塞 | 使用 requestAnimationFrame + 時間差計算、或 Web Worker |
| 標題列過長被截斷 | 瀏覽器分頁寬度限制 | 縮短格式、僅顯示時分、或僅在頁面區域顯示 |
| 時區錯誤 | 伺服器/用戶端時區不一致 | 明確指定時區、或使用 UTC 時間統一換算 |
| 多標籤頁同步問題 | 各標籤獨立計時器 | SharedWorker 或 BroadcastChannel 同步主時鐘 |
| 記憶體洩漏 | 未清理 setInterval | beforeunload / visibilitychange 正確清理 |
Intl.DateTimeFormat 實例,不同 timeZoneIntl.RelativeTimeFormat 顯示「3 分鐘前」、「2 小時後」chinese-calendar)<time datetime="2024-12-25T14:30:05+08:00"> 機器可讀時間aria-live="polite" 讓螢幕閱讀器定期宣告 (避免過於頻繁)HTML5 + JS 即時時鐘的核心極簡:new Date() → 格式化 → 寫入 DOM → setInterval 循環。現代開發請優先使用 Intl.DateTimeFormat 處理地區化格式,配合 Visibility API 優化背景分頁資源佔用,並妥善清理定時器。若需高精度同步,可引入 NTP 對時或 WebSocket 伺服器推送時間。