# 使用 JS 实现打字机效果

<div class="container"></div>
1
class Typing {
  constructor(options = {}) {
    this.msg = options.msg || ''
    this.el = options.el || document.querySelector('.container') //容器
    this.index = options.index || 0
    this.speed = options.speed || 200 //控制打字时间(ms)
    this.timer = options.timer || null
    this.setStyle()
  }
  len() {
    return this.msg.length
  }
  setStyle() {
    window.onload = () => {
      this.el.style.setProperty('white-space', 'pre-wrap')
      // 添加伪元素样式
      document.styleSheets[0].addRule(
        '.container::after',
        `content: '';height: 16px;border-right: 3px solid;animation: effect 0.5s step-end infinite alternate`
      )
      document.styleSheets[0].addRule(
        '@keyframes effect',
        `50% {border-color: transparent;}`
      )
    }
  }
  type() {
    const _this = this
    const lastWord = this.msg.substring(this.index, this.index + 1)
    this.el.innerHTML += lastWord
    if (this.index >= this.len()) {
      this.index = 0
      clearTimeout(this.timer)
    } else {
      this.index++
      this.timer = setTimeout(() => this.type(), this.speed)
    }
  }
}

const typeWord = new Typing({
  speed: 100,
  msg: `五月伊始,春深夏浅。
      一川绿韵,洇润心间。一缕微风,安暖心田。一点人间烟火,与心情共舞,同流云为伴。
      再念那,一径芳草,一帘流光。驾小车,走山脚小道,行十里山路,回到故里。那个让人缱绻的小山村。
      故园袖珍,5户3阶6口人,3群羊,3只狗,1头牛。日影是最好的钟表,月相是最准的日历。晨来,一缕晨曦越山丫。云走雾潮,绿浓山润。羊咩狗汪牛哞哞,鸟歌兔跑雕嘎嘎。随势开田,耕种薄田。`
})
typeWord.type()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

dailyQuestion