打字动画 js版

950 阅读1分钟

前言

打字动画 CSS 中,我们使用了 css 来实现打字动画,效果也不错。但是它依赖了等宽字体,不是等宽字体的话,效果会大打折扣;同时要实现一些复杂的动画的话,还是得使用 js 去做控制。

js 简单版

我们用 js 来实现一个简单版本。

DOM 结构为

<span id="container"></span><span class="typing">_</span>

光标依旧使用 css 来处理,添加一个闪烁动画

    @keyframes caret {
      from {
        color: transparent;
      }
    }
    .typing {
      font-weight: 600;
      animation: caret 1s steps(2) infinite;
    }

打字效果,就是将文字拆开,然后拆开的文字定时添加到 container

    let wordList = 'hello world!'.split('')
    let animationDom = document.getElementById('container')
    let timer = -1
    let animation = () => {
      if (wordList.length > 0) {
        animationDom.innerText += wordList.shift()
        timer = setTimeout(animation, 600)
      } else {
        clearTimeout(timer)
      }
    }
    animation()

最终效果

GSAP 版本

gsap 提供了文字处理相关的插件,实现起来也比较简单。

引入 gsap 和 gsap TextPlugin

  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.4.2/gsap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.4.2/TextPlugin.min.js"></script>

DOM 结构为

<span class="text2"></span><span class="cursor">_</span>

光标处理, opacity 从 0 变到 1,repeat 为 -1 表示无限重复,然后再添加一个缓动动画,让效果更逼真一些

gsap.to('.cursor', { opacity: 0, repeat: -1, ease: "power2.inOut"})

文字处理,这个比较简单

gsap.to('.text2', { duration: 4, text: 'hello world!', ease: 'none' })

当然,我们还可使用 gsap 做更多复杂的打字动画。 DOM 结构

<span class='hi'>Hi, 我是</span><span class="text"></span><span class="cursor">_</span>
    const words = ["一个打工人。", "一个干饭人。", "一个程序员。"]
    
    gsap.to('.cursor', { opacity: 0, repeat: -1, ease: "power2.inOut"})

    let masterTl = gsap.timeline({delay: 1, repeat: -1,})
    words.forEach(word => {
      let tl = gsap.timeline({ repeat: 1, yoyo: true, repeatDelay: 1 })
      tl.to('.text', { duration: 1.5, text: word })
      masterTl.add(tl)
    })

其他 typing 动画库

还有一些专门做打字动画的库: