瀏覽器分頁上那行標題,其實可以透過 document.title 隨時改寫。搭配計時器,就能做出會跳動的動態標題——最經典的應用就是即時時鐘。
document.title 對應的就是頁面的標題文字,直接赋值即可:
<html> <head> <title></title> </head> <body> <script type="text/javascript"> document.title = "我是網頁title"; </script> </body> </html>
setTimeout 接受兩個參數,第一個是要執行的函式,第二個是延遲的毫秒數:
setTimeout("test()", 1000);
<html>
<head>
<title>測試title</title>
</head>
<body>
<script type="text/javascript">
function flashTitle(){
time = new Date();
str = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
document.title = " " + str;
setTimeout("flashTitle()", 1000);
}
flashTitle();
</script>
</body>
</html>
測試時發現一個小差異:在 IE 下實作動態時間標題,字串前面必須先墊一個空白字元(或任意字元)才會正常刷新,否則可能沒有反應。
1. 用 setInterval 取代遞迴 setTimeout。每秒重排一個計時器的寫法容易在頁面隱藏時累積多餘排程,改成一次建立即可:
function pad(n){ return ('0' + n).slice(-2); }
function renderTitle(){
var d = new Date();
document.title = ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
}
setInterval(renderTitle, 1000);
renderTitle();
順帶解決了另一個問題:原版的分與秒在個位數時不會補零,畫面會變成 9:5:3 這種不齊的樣子。
2. 為變數加上 var。原範例中 time、str 都是隱性全域變數,在嚴格模式下會直接報錯。
3. 記得在頁面卸載時清除計時器。若是單頁應用,切換頁面後殘留的計時器會繼續改寫標題:
var timerId = setInterval(renderTitle, 1000);
window.addEventListener('beforeunload', function(){ clearInterval(timerId); });
4. 動態標題要節制使用。閃爍或跳動的標題在早期很常見,但對使用螢光筆-reading 的使用者、以及需要靠標題辨識分頁的人來說,每秒變動一次的文字其實是干擾。若目的是提醒使用者注意,更友善的做法是「只在有新事件時短暫變更,並在焦點回到頁面後還原」。