CSS实现打字机效果

文章访问量:

animation: steps(n)

先来看看打字机效果是什么。

早上好,中国。现在我有冰淇淋。

em与animation:steps(n)

相对长度单位与逐帧动画

浏览器默认字体尺寸就是1em,即16px。一个标点符号就是0.5em,即8px。

接下来是animation。在animation指定step(n),动画就会分为n步进行。

那么打字机效果实现的思路就是:动态增长文本的长度(@keyframe),同时将文本的右边框当作“|”光标(border-right),再给光标加个transparent的animation即可。

示例

有着15个字符字符串

给定一个15个字符的字符串,那么先计算有多少em。如果末尾是句号的话可以当0.5em算,这样最好光标会紧贴着末尾的字符。

这里我们给定的字符串一共15em,去掉0.5em的话就是14.5em。

早上好,中国。现在我有冰淇淋。

那么动画我们分15步走,相当于实现一个“逐字显示”的效果。

<h6 style="color: #08fdc3;font-style: italic;" class="currentReading">早上好,中国。现在我有冰淇淋。</h6>
<style>
  .currentReading {
      width: 14.5em;
      animation: typingWords 10s steps(15) infinite, cursor 0.5s steps(1) infinite;
      white-space: nowrap;
      overflow: hidden;
      border-right: 1px solid #08fdc3;
  }

  @keyframes typingWords {
      0% {
          width: 0;
      }
      15% {
          width:6.5em;
      }
      30% {
          width: 6.5em;
      }
      45% {
          width: 14.5em;
      }
      100% {
          width: 14.5em;
      }
  }

  @keyframes cursor {
      50% {
          border-color: transparent;
      }
  }

</style>

实现效果和文章开头的一样。通过修改steps(x)的值还可以得到不同的打字机效果,建议自行尝试。

Subscribe
提醒
0 评论
Inline Feedbacks
View all comments
0
在此留下你的评论x