萬盛學電腦網

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

JavaScript 實現動態網頁標題:document.title 與 setInterval/RequestAnimationFrame 完整指南

前言

動態修改瀏覽器標籤頁標題 (document.title) 是提升用戶感知、通知新消息、顯示即時狀態的常用技巧。本文系統講解從基礎計時器標題、閃爍提醒、進度條標題到現代 requestAnimationFrame 高效能實現的完整方案。

一、基礎 API:document.title

// 獲取當前標題
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(); };

四、現代高效能實現:requestAnimationFrame + 狀態機

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();

五、實戰應用模式

1. 未讀消息計數徽章

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); // 聚焦時清零
});

2. 表單填寫進度提示

var steps = ['基本資料', '聯繫方式', '偏好設置', '完成'];
var currentStep = 0;

function updateStepTitle(stepIndex) {
    currentStep = stepIndex;
    document.title = '步驟 ' + (stepIndex + 1) + '/' + steps.length + ': ' + steps[stepIndex] + ' - 註冊向導';
}

3. 影音播放狀態

var video = document.querySelector('video');
video.addEventListener('play', () => document.title = '▶️ ' + originalTitle);
video.addEventListener('pause', () => document.title = '⏸ ' + originalTitle);
video.addEventListener('ended', () => document.title = '✅ ' + originalTitle);

六、最佳實踐與避坑指南

  1. 保存原始標題:初始化時 const originalTitle = document.title,銷毀/停止時恢復。
  2. 尊重用戶注意力:閃爍頻率 ≤ 1Hz,提供關閉開關,頁面聚焦自動停止。
  3. 編碼安全:標題中包含用戶輸入內容時,需轉義或限制長度,防 XSS (雖然 title 不執行 HTML,但可能影響日誌/書籤)。
  4. SEO 影響:爬蟲通常只抓取初始 HTML <title>,動態修改不影響 SEO,但避免核心關鍵詞被動態移除。
  5. 跨域 iframe 限制:iframe 內修改 top.document.title 受同源策略限制。

七、TypeScript 類型定義 (供參考)

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 方案,獲得最佳效能與用戶體驗。

copyright © 萬盛學電腦網 all rights reserved