利用 document.title 修改頁面標題,配合 setTimeout / setInterval 定時切換標題文字,產生閃爍視覺效果,提醒使用者有新訊息。點擊頁面任意處可停止閃爍並恢復原標題。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS 標題閃爍提醒示範</title>
<style>
body { font-family: sans-serif; padding: 40px; line-height: 1.6; }
.btn { padding: 10px 20px; margin: 5px; cursor: pointer; border: none; border-radius: 4px; }
.btn-primary { background: #007bff; color: white; }
.btn-success { background: #28a745; color: white; }
.log { margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 4px; font-family: monospace; font-size: 14px; max-height: 200px; overflow-y: auto; }
</style>
</head>
<body>
<h2>瀏覽器標題閃爍提醒示範</h2>
<p>點擊下方按鈕觸發閃爍,再點擊頁面任意處或「停止閃爍」按鈕恢復。</p>
<button class="btn btn-primary" id="btnStartFlash">開始閃爍 (新訊息)</button>
<button class="btn btn-success" id="btnStopFlash">停止閃爍</button>
<button class="btn btn-secondary" id="btnSimulateMsg">模擬收到訊息</button>
<div class="log" id="log">日誌輸出區...</div>
<script>
// ==================== 核心閃爍邏輯 (封裝為可複用模組) ====================
var TitleFlasher = (function() {
var originalTitle = document.title;
var timerId = null;
var flashCount = 0;
var isFlashing = false;
var flashInterval = 800; // 閃爍間隔 (ms)
var flashTitle = "【 新訊息 】";
var emptyTitle = "【 】";
function log(msg) {
var $log = $("#log");
$log.prepend("<div>[" + new Date().toLocaleTimeString() + "] " + msg + "</div>");
}
function toggleTitle() {
flashCount++;
document.title = (flashCount % 2 === 0) ? emptyTitle + " " + originalTitle
: flashTitle + " " + originalTitle;
}
return {
start: function(customTitle, interval) {
if (isFlashing) return; // 防重複啟動
originalTitle = document.title; // 記錄當前標題 (可能已被改過)
flashTitle = customTitle || "【 新訊息 】";
flashInterval = interval || 800;
flashCount = 0;
isFlashing = true;
// 立即執行一次
toggleTitle();
// 週期性切換
timerId = setInterval(toggleTitle, flashInterval);
log("▶ 開始閃爍: " + flashTitle);
// 綁定點擊頁面停止 (只綁定一次)
if (!this._bound) {
$(document).one("click keydown", this.stop.bind(this));
this._bound = true;
}
},
stop: function() {
if (!isFlashing) return;
clearInterval(timerId);
timerId = null;
document.title = originalTitle;
isFlashing = false;
this._bound = false;
log("■ 停止閃爍,恢復標題: " + originalTitle);
},
isActive: function() {
return isFlashing;
}
};
})();
// ==================== 事件綁定 ====================
$("#btnStartFlash").click(function() {
TitleFlasher.start("【 新訊息 】", 800);
});
$("#btnStopFlash").click(function() {
TitleFlasher.stop();
});
$("#btnSimulateMsg").click(function() {
// 模擬收到訊息:若已在閃爍則更新訊息,否則開始閃爍
if (TitleFlasher.isActive()) {
TitleFlasher.stop();
}
TitleFlasher.start("【 3 條未讀訊息 】", 600);
});
// 頁面可見性變化:切回分頁時自動停止
document.addEventListener("visibilitychange", function() {
if (!document.hidden && TitleFlasher.isActive()) {
TitleFlasher.stop();
}
});
</script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
</html>
var TitleFlasher = (function() {
var originalTitle = document.title;
var timerId = null;
var mode = "alternate"; // alternate | prefix | suffix | scroll
var customMessage = "新訊息";
var modes = {
alternate: function(count) { // 交替顯示
return (count % 2 === 0) ? "【 】 " + originalTitle
: "【 " + customMessage + " 】 " + originalTitle;
},
prefix: function(count) { // 前綴閃爍
return (count % 2 === 0) ? "● " + originalTitle
: "○ " + originalTitle;
},
suffix: function(count) { // 後綴閃爍
return originalTitle + (count % 2 === 0 ? " ●" : " ○");
},
scroll: function(count) { // 跑馬燈 (需較長間隔)
var msg = " ◆ " + customMessage + " ◆ ";
var pos = count % (msg.length + originalTitle.length);
return (msg + originalTitle + msg).substr(pos, originalTitle.length + 10);
}
};
return {
start: function(message, interval, flashMode) {
if (timerId) clearInterval(timerId);
originalTitle = document.title;
customMessage = message || "新訊息";
mode = flashMode || "alternate";
var count = 0;
timerId = setInterval(function() {
document.title = modes[mode](count++);
}, interval || 800);
},
stop: function() {
clearInterval(timerId);
timerId = null;
document.title = originalTitle;
}
};
})();
function notifyAndFlash(title, body) {
// 1. 標題閃爍
TitleFlasher.start("【 " + title + " 】");
// 2. 瀏覽器桌面通知 (需權限)
if ("Notification" in window && Notification.permission === "granted") {
new Notification(title, {
body: body,
icon: "/favicon.ico",
tag: "app-notification" // 避免重複堆疊
});
} else if ("Notification" in window && Notification.permission !== "denied") {
Notification.requestPermission().then(function(permission) {
if (permission === "granted") {
new Notification(title, { body: body });
}
});
}
// 3. 声音提醒 (可選)
// var audio = new Audio("/sounds/notify.mp3");
// audio.play().catch(() => {}); // 忽略自動播放限制錯誤
}
// React Hook 版
import { useEffect, useRef } from 'react';
function useTitleFlash(message, isActive, interval = 800) {
const originalTitle = useRef(document.title);
const timerRef = useRef(null);
const countRef = useRef(0);
useEffect(() => {
if (isActive) {
originalTitle.current = document.title;
countRef.current = 0;
timerRef.current = setInterval(() => {
countRef.current++;
document.title = countRef.current % 2 === 0
? `【 】 ${originalTitle.current}`
: `【 ${message} 】 ${originalTitle.current}`;
}, interval);
} else {
clearInterval(timerRef.current);
document.title = originalTitle.current;
}
return () => clearInterval(timerRef.current);
}, [isActive, message, interval]);
}
// 使用
function App() {
const [hasNewMsg, setHasNewMsg] = useState(false);
useTitleFlash("新訊息", hasNewMsg);
return ;
}
| 特性 | 支援情況 | 備註 |
|---|---|---|
document.title 修改 | 所有瀏覽器 | 核心功能全支援 |
setInterval | 所有瀏覽器 | 背景分頁可能降低頻率 (最低 1Hz) |
| 頁面可見性 API | IE10+、所有現代瀏覽器 | document.visibilityState、visibilitychange 事件 |
| Notification API | Chrome 22+、Firefox 22+、Safari 16+ | 需 HTTPS、使用者授權、非跨域 iframe |
| Favicon 閃爍 | 較複雜 | 需預載多張 favicon,用 link[rel="icon"] 切換 |
document.title,停止時精確恢復@media (prefers-reduced-motion))標題閃爍是輕量級的新訊息提醒手段,核心實作極簡單:setInterval 切換 document.title。生產環境建議封裝為可複用模組 (如文中的 TitleFlasher),整合頁面可見性 API 自動停止、桌面通知 API 增強觸達率、提供多種閃爍模式適應不同場景。注意瀏覽器背景分頁會降低定時器頻率,閃爍效果可能變慢,這是正常的節能機制。