打字动画

360 阅读1分钟

打字效果是常见的动画,它靠 CSS 和等宽字体就可以实现。

原理

这个技巧主要使用了 CSS 属性 animation steps 来控制文本容器的宽度,使宽度以一定速度突变,就便表现出打字的效果。核心代码如下:

#text {
  display: inline-block;
  width: 23ch; /*以字符宽度为单位*/
  animation: textShow 3s steps(23) infinite; /*steps(字数+1)*/
}

width 和 steps 的参数根据字数来调整。 为了使得文字不会换行,且在宽度之外的文字被隐藏,还需要加上下面的 CSS 属性:

#text {
  overflow: hidden;
  word-break: keep-all;
  white-space: nowrap;
}

这样文本的出现便呈现出打字动画效果。

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>打字效果</title>

    <style>
      * {
        padding: 0;
        margin: 0;
      }
      html {
        font-family: Consolas;
        font-size: 20px;
      }
      body {
        overflow: hidden;
        width: 100vw;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      #text {
        overflow: hidden;
        display: inline-block;
        width: 23ch;
        word-break: keep-all;
        white-space: nowrap;
        vertical-align: center;
        animation: textShow 3s steps(23) infinite; /*steps(字数+1)*/
      }
      @keyframes textShow {
        0% {
          width: 0;
        }
      }

      #cursor {
        animation: cursorBlink 1s infinite;
      }
      @keyframes cursorBlink {
        0% {
          opacity: 0;
        }
        50% {
          opacity: 1;
        }
        100% {
          opacity: 0;
        }
      }
    </style>
  </head>
  <body>
    <div id="animeText">
      <span id="text">Text typing animation.</span>
      <span id="cursor">_</span>
    </div>
  </body>
</html>