萬盛學電腦網

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

純 JavaScript 實現打字機效果:無依賴、支援多語言循環

打字機效果常用於 Hero 區塊、標語輪播。本文提供零依賴、約 50 行的現代實作,支援多字詞循環、打字/刪字速度可配、暫停/恢復、無障礙友善。

核心邏輯:狀態機

class Typewriter {
  constructor(el, words, { typeSpeed = 100, deleteSpeed = 50, delay = 2000 } = {}) {
    this.el = el;
    this.words = words;
    this.typeSpeed = typeSpeed;
    this.deleteSpeed = deleteSpeed;
    this.delay = delay;
    this.wordIndex = 0;
    this.charIndex = 0;
    this.isDeleting = false;
    this.timer = null;
  }

  start() { this.tick(); }
  stop() { clearTimeout(this.timer); }

  tick() {
    const current = this.words[this.wordIndex];
    const full = current.slice(0, this.charIndex);
    this.el.textContent = full + (this.isDeleting ? '' : '|'); // 游標

    if (!this.isDeleting && this.charIndex === current.length) {
      // 打字完成,等待 delay 後開始刪字
      this.isDeleting = true;
      this.timer = setTimeout(() => this.tick(), this.delay);
      return;
    }
    if (this.isDeleting && this.charIndex === 0) {
      // 刪除完成,切換下一個詞
      this.isDeleting = false;
      this.wordIndex = (this.wordIndex + 1) % this.words.length;
      this.timer = setTimeout(() => this.tick(), 500);
      return;
    }

    // 繼續打字/刪字
    this.charIndex += this.isDeleting ? -1 : 1;
    this.timer = setTimeout(() => this.tick(), this.isDeleting ? this.deleteSpeed : this.typeSpeed);
  }
}

HTML 與啟用

<h1>We provide <span id="typewriter" aria-live="polite"></span></h1>
<script>
  new Typewriter(document.getElementById('typewriter'), [
    'knowledge', 'community', 'an outlet', '中國起源', 'OSCHINA'
  ], { typeSpeed: 80, deleteSpeed: 40, delay: 1500 }).start();
</script>

進階增強

  • HTML 內容支援:用 innerHTML 替代 textContent,允許 <strong>、<em> 等標籤(需防 XSS)。
  • 無障礙:容器加 aria-live="polite",螢幕閱讀器可朗讀變化;提供「暫停動畫」開關(prefers-reduced-motion 媒體查詢自動停止)。
  • 響應式速度:根據字詞長度動態調整速度,避免過長單詞等待過久。
  • TypeScript 型別:補全介面定義,提升維護性。

CSS 游標動畫(可選)

@keyframes blink { 50% { opacity: 0; } }
#typewriter::after { content: '|'; animation: blink 1s infinite; }

此實作無任何外部依賴,gzip < 1KB,可直接嵌入專案或作為 Web Component (<type-writer words="...">) 複用。

copyright © 萬盛學電腦網 all rights reserved