打字機效果常用於 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);
}
}
<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>
innerHTML 替代 textContent,允許 <strong>、<em> 等標籤(需防 XSS)。aria-live="polite",螢幕閱讀器可朗讀變化;提供「暫停動畫」開關(prefers-reduced-motion 媒體查詢自動停止)。@keyframes blink { 50% { opacity: 0; } }
#typewriter::after { content: '|'; animation: blink 1s infinite; }
此實作無任何外部依賴,gzip < 1KB,可直接嵌入專案或作為 Web Component (<type-writer words="...">) 複用。