本文示範如何用 JavaScript 模擬鍵盤逐字打字的動畫效果,讓一段文字像被一個個字打出來那樣顯示。
$(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()();
});
總結:為了實現每次循環間隔一段時間,採用 window.setTimeout 遞迴的寫法;由於想用原型鏈封裝而產生 this 衝突,所以遞迴呼叫匿名閉包函式,並以 arguments.callee 表示該匿名函式。
HTML 結構如下(.content 為要打字顯示的文字,.div1 為輸出區):
<button id="pri">pri</button> <div class="content" style="display: none;"> 在這裡放入一段要逐字顯示的文字內容…… </div> <div class="div1"></div>
透過把文字拆成字元陣列,再用 setTimeout 逐一 append,就能呈現自然的打字動畫。