以程式碼形式說明實作過程:透過 setInterval 反覆呼叫同一個函式,每次用 substring 多取一個字,就能模擬逐字輸出的打字機效果;一則播完後停頓一段時間,再換下一則。
<html>
<head>
<title>打字效果</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style type="text/css">
body { font-size:14px; font-weight:bolder; }
</style>
</head>
<body>
最新內容:
<a id="Hotnews" href="" target="_blank"></a>
<script language="javascript">
var NewsTime = 2000; // 每則訊息完整出現後的停留時間
var TextTime = 100; // 每個字出現的間隔時間
var newsi = 0; // 目前是第幾則
var txti = 0; // 目前顯示到第幾個字
var txttimer; // setInterval 的返回值,用於取消週期性執行
var newstimer;
var newstitle = new Array(); // 各則訊息的標題
var newshref = new Array(); // 標題對應的連結
newstitle[0] = "歡迎來到我的部落格";
newshref[0] = "https://example.com/";
newstitle[1] = "https://example.com/";
newshref[1] = "https://example.com/";
newstitle[2] = "歡迎你哦";
newshref[2] = "https://example.com";
newstitle[3] = "ByeBye~~";
newshref[3] = "https://example.com";
function shownew() {
var hwnewstr = newstitle[newsi]; // 依 newsi 依序取出內容
var newslink = newshref[newsi]; // 對應的連結
// 已完整顯示這一則,切換到下一則
if (txti >= hwnewstr.length) {
clearInterval(txttimer);
clearInterval(newstimer);
newsi++;
if (newsi >= newstitle.length) newsi = 0; // 回到第一則
newstimer = setInterval(shownew, NewsTime);
txti = 0;
return;
}
clearInterval(txttimer);
document.getElementById("Hotnews").href = newslink;
document.getElementById("Hotnews").innerHTML = hwnewstr.substring(0, txti + 1);
txti++; // 文字一個個出現
txttimer = setInterval(shownew, TextTime);
}
shownew();
</script>
</body>
</html>
這段程式碼的骨架很值得記住:一個計時器負責字級推進,另一個負責則間切換,兩者互相 clear 再重設,形成接力。不過原寫法有兩個可改進處:一是 setInterval 搭配 clearInterval 的組合其實可以直接寫成 setTimeout 遞迴,語意更清楚;二是把元素查詢結果快取起來,避免每 100 毫秒查一次 DOM。
簡化後的版本如下:
var el = document.getElementById("Hotnews");
var idx = 0, len = 0, text = "";
function type() {
if (len <= text.length) {
el.textContent = text.substring(0, len++);
setTimeout(type, 100);
} else {
idx = (idx + 1) % list.length;
text = list[idx].title;
el.href = list[idx].href;
len = 0;
setTimeout(type, 2000);
}
}
另外,原範例用 innerHTML 寫入文字,若訊息來源可能是使用者輸入或外部資料,應改用 textContent 以避免 XSS 風險。