萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 打字機效果:逐字顯示動畫

核心邏輯

  • 將目標文字拆分為字元陣列
  • 使用 setTimeout 遞歸,每 100ms 追加一個字元
  • 利用閉包保存 this 上下文與索引狀態

實現代碼

var input_type = {
    init: function($obj) {
        this.chars = $obj.html().split("");
        this.length = this.chars.length;
        this.i = 0;
    },
    pri: function() {
        var $this = this;
        return (function next() {
            if ($this.i >= $this.length) return;
            $(".div1").append($this.chars[$this.i++]);
            setTimeout(next, 100);
        })();
    }
};

function Input_type() { this.init.apply(this, arguments); }
Input_type.prototype = input_type;

// 使用
$(function() {
    var p = new Input_type($(".content"));
    p.pri();
});

HTML 結構

<div class="content" style="display:none">這裡放要打字顯示的長文本...</div>
<div class="div1"></div> <!-- 顯示容器 -->

關鍵技術點

  • arguments.callee(已棄用)或具名函數 next() 實現遞歸
  • 閉包捕獲 this 避免 setTimeout 上下文丟失
  • 原型模式封裝,便於多實例複用

現代寫法可改用 async/await + Promise 更優雅。

copyright © 萬盛學電腦網 all rights reserved