把一段文字一個字一個字慢慢顯示出來,是很多首頁與履歷頁會用的效果。原理不難:把字串拆成陣列,用計時器逐個 append。真正需要小心的是 this 指向與遞迴的寫法。
$(function () {
var input_type = {
init: function ($obj) {
this.name = $obj.html().split("");
this.length = this.name.length;
this.i = 0;
},
pri: function () {
var $this = this;
// 這裡只能用閉包:window.setTimeout 會讓 this 指向 window,
// 而非原型鏈上的 this 物件。因為需要遞迴,只能把 this 傳進閉包。
return (function () {
if ($this.i > $this.length) {
window.clearTimeout(Go);
return false;
}
var char = $this.name;
$(".div1").append(char[$this.i]);
$this.i++;
var Go = window.setTimeout(arguments.callee, 100);
// arguments.callee 指向這個匿名函式本身,用來做遞迴
}());
}
};
// 建立 class
function Input_type() { this.init.apply(this, arguments); }
Input_type.prototype = input_type;
// 建立實例
var p = new Input_type($(".content"));
p.pri()();
});
兩個關鍵點值得說明。
第一,this 的指向。計時器回呼會以 window 為 this,因此必须把外層的 this 存成 $this 再帶進去,否則 this.i++ 會改到 window 上。
第二,arguments.callee。因為回呼是匿名函式,沒有名字可以遞迴呼叫,於是透過 arguments.callee 取得函式自身。這招能用,但要注意:callee 在 strict mode 下已被禁用,而且會妨礙引擎做 inline 優化。
把回呼命名,就不必依賴 callee,也不必用閉包傳 this:
var el = document.querySelector('.div1');
function typeText(text, index) {
if (index >= text.length) return;
el.append(text[index]);
setTimeout(function () { typeText(text, index + 1); }, 100);
}
typeText(document.querySelector('.content').textContent, 0);
用 async/await 會更像在描述流程:
function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
async function type(el, speed) {
const text = el.textContent;
el.textContent = '';
for (const char of text) {
el.textContent += char;
await sleep(speed);
}
}
注意這裡用 for...of 而非 split(""):後者會把 emoji 與部分中日文字元切成半個代理對,顯示出來就是亂碼。用 [...text] 或 for...of 才能正確按「使用者看到的一個字」迭代。
<button id="pri">開始</button> <div class="content" style="display: none;"> 我與父親不相見已二年余了,我最不能忘記的是他的背影。 那年冬天,祖母死了,父親的差使也交卸了,正是禍不單行的日子。 </div> <div class="div1"></div>
從 display:none 讀字會有陷阱。用 html() 讀隱藏元素時,瀏覽器可能回傳被正規化過的內容。比較穩妥的做法是把文字放在 <script type="text/plain"> 或 data 屬性裡。
用 textContent 而非 append 逐字插入。每次 append 都會觸發版面計算;累積到字串再一次性寫入 el.textContent += char 反而更省,或者反過來在真正需要時才寫入。
記得尊重使用者的動效偏好。對部分使用者而言,逐字出現的文字會造成閱讀障礙:
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
el.textContent = text; // 直接顯示全文
return;
}
這個小效果示範了一個通則:當你直覺想用 arguments.callee 或閉包傳 this 時,通常意味著把回呼命名、或改用 async/await,就能讓意圖變得更直白。