動態修改瀏覽器標籤頁標題 (document.title) 是提升用戶感知、通知新消息、顯示即時狀態的常用技巧。本文系統講解從基礎計時器標題、閃爍提醒、進度條標題到現代 requestAnimationFrame 高效能實現的完整方案。
// 獲取當前標題
var current = document.title; // "原始標題"
// 設置新標題
document.title = "新標題內容";
// 特性:
// - 同步操作,立即生效
// - 僅接受字符串,非字符串會自動 toString()
// - 過長會被瀏覽器截斷 (通常 50-100 字符)
// - 不支持 HTML 標籤,實體會被轉義顯示
function startClockTitle() {
function update() {
var now = new Date();
var h = String(now.getHours()).padStart(2, '0');
var m = String(now.getMinutes()).padStart(2, '0');
var s = String(now.getSeconds()).padStart(2, '0');
document.title = h + ':' + m + ':' + s + ' - 我的網站';
}
update(); // 立即執行一次
setInterval(update, 1000); // 每秒更新
}
startClockTitle();
var TitleFlasher = (function() {
var originalTitle = document.title;
var timer = null;
var isFlashing = false;
function flash(newTitle, interval) {
if (isFlashing) return;
isFlashing = true;
var showNew = true;
timer = setInterval(function() {
document.title = showNew ? newTitle : originalTitle;
showNew = !showNew;
}, interval || 1000);
}
function stop() {
if (!isFlashing) return;
clearInterval(timer);
document.title = originalTitle;
isFlashing = false;
}
return { flash: flash, stop: stop, originalTitle: originalTitle };
})();
// 使用示例:收到新消息
// socket.on('message', function() { TitleFlasher.flash('🔔 新消息 (3)'); });
// 用戶點擊頁面/聚焦窗口
// window.onfocus = function() { TitleFlasher.stop(); };
setInterval 在後台標籤頁會被瀏覽器節流 (最小 1000ms),導致動畫卡頓。requestAnimationFrame (rAF) 配合時間戳可實現**前台高幀率、後台自動暫停**的最佳體驗。
class DynamicTitle {
constructor(options = {}) {
this.originalTitle = document.title;
this.patterns = options.patterns || []; // [{ text: '...', duration: 2000 }, ...]
this.index = 0;
this.startTime = 0;
this.rafId = null;
this.running = false;
this.hidden = document.hidden;
// 頁面可見性變化自動暫停/恢復
document.addEventListener('visibilitychange', () => {
this.hidden = document.hidden;
if (this.hidden) this.pause();
else this.resume();
});
}
// 啟動循環播放
start(patterns) {
if (patterns) this.patterns = patterns;
if (!this.patterns.length) return;
this.running = true;
this.index = 0;
this.startTime = performance.now();
this._tick();
}
_tick() {
if (!this.running) return;
var now = performance.now();
var elapsed = now - this.startTime;
var current = this.patterns[this.index];
if (elapsed >= current.duration) {
this.index = (this.index + 1) % this.patterns.length;
this.startTime = now;
current = this.patterns[this.index];
}
document.title = current.text;
this.rafId = requestAnimationFrame(() => this._tick());
}
pause() {
this.running = false;
cancelAnimationFrame(this.rafId);
document.title = this.originalTitle;
}
resume() {
if (this.patterns.length) this.start();
}
// 一次性閃爍
flashOnce(text, duration) {
this.pause();
document.title = text;
setTimeout(() => this.resume(), duration || 2000);
}
destroy() {
this.pause();
document.removeEventListener('visibilitychange', this._visibilityHandler);
}
}
// 使用示例
var dt = new DynamicTitle({
patterns: [
{ text: '📝 編輯文檔 - 我的應用', duration: 3000 },
{ text: '💾 已自動保存', duration: 1500 },
{ text: '☁️ 同步中...', duration: 2000 }
]
});
dt.start();
function setUnreadCount(count) {
if (count > 0) {
document.title = '(' + count + ') ' + originalTitle;
} else {
document.title = originalTitle;
}
}
// 配合 Page Visibility API
document.addEventListener('visibilitychange', function() {
if (!document.hidden) setUnreadCount(0); // 聚焦時清零
});
var steps = ['基本資料', '聯繫方式', '偏好設置', '完成'];
var currentStep = 0;
function updateStepTitle(stepIndex) {
currentStep = stepIndex;
document.title = '步驟 ' + (stepIndex + 1) + '/' + steps.length + ': ' + steps[stepIndex] + ' - 註冊向導';
}
var video = document.querySelector('video');
video.addEventListener('play', () => document.title = '▶️ ' + originalTitle);
video.addEventListener('pause', () => document.title = '⏸ ' + originalTitle);
video.addEventListener('ended', () => document.title = '✅ ' + originalTitle);
const originalTitle = document.title,銷毀/停止時恢復。<title>,動態修改不影響 SEO,但避免核心關鍵詞被動態移除。top.document.title 受同源策略限制。interface TitlePattern {
text: string;
duration: number; // ms
}
interface DynamicTitleOptions {
patterns?: TitlePattern[];
}
declare class DynamicTitle {
constructor(options?: DynamicTitleOptions);
start(patterns?: TitlePattern[]): void;
pause(): void;
resume(): void;
flashOnce(text: string, duration?: number): void;
destroy(): void;
}
document.title 是一個極簡卻強大的 UI 介面。從簡單的時鐘到複雜的狀態機驅動標題,**核心原則是:保存原狀、尊重可見性、控制頻率、提供清理**。現代專案請優先使用 requestAnimationFrame + visibilitychange 方案,獲得最佳效能與用戶體驗。