如何仅通过css快速实现打字动效

fox/ 2023年08月01日/ CSS教程/ 浏览 527

在一些交互较多的网站上,我们经常能见到类似打字机输入文字的效果,在 CSS 动画的控制下,我们可以通过仅使用 animation 和 @keyframes 属性去实现打字效果。


这里仅为大家提供一个基础的打字效果。很多开发者会使用 JavaScript 库去实现,而不是使用 CSS。

参考结构如下:


<div class="typing-box">
    <div class="typing-act">Typing effect for text</div>
</div>


参考css如下:


.typing-box {
  height: 80vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.typing-act {
  width: 22ch;
  white-space: nowrap;
  overflow: hidden;
  border-right: 3px solid;
  font-family: monospace;
  font-size: 2em;
  animation: typing 2s steps(22), effect .5s step-end infinite alternate;
}

@keyframes typing {
  from {
    width: 0;
  }
}

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


这里,我们通过 steps() 属性来实现分割文本的效果。首先,你必须指定 step() 中传入的数量,在这个例子中就是文本的长度。


接着,我们使用 @keyframes 去声明什么时候开始执行动画。


打字速度大家可以调整 .typing-ac的animation参数

打字区域宽度大家可以调整 .typing-act 的宽度参数

发表评论

暂无评论,抢个沙发...

客服 工单