css 打字动画

使用 css 将文字逐字打出

<h1>css is awesome</h1>

要使<h1>标签里的文字逐字打出,对应的样式如下:

  h1{
    width: 14ch;/×文本的宽度×/
    overflow: hidden;
    white-space: nowrap;
    border-right: .05em solid transparent;
    animation: typing 4s steps(14),
              caret 1s steps(1) infinite;

  }
  @keyframes typing{
    from{ width: 0 }
  }
  @-webkit-keyframes typing{
    from{ width: 0 }
  }
  @keyframes caret{
    50%{
      border-color: currentColor;
    }
  }
  @-webkit-keyframes caret{
    50%{
      border-color: currentColor;
    }
  }

ch单位是css3引入的一个新单位,表示“0”字形的宽度,在等宽字体中,“0”字形的宽度和其他所有字形的宽度一样。

例子中用ch表示这个标题的宽度,取值就是字符的数量,为14。

由于h1标签里的文字可能有变化,为此引入如下js:

var len = $("h1").text().length;
$("h1").css("width",len+"ch");
$("h1").css("animationTimingFunction","steps("+len+"),steps(1)");