大家好,我是 Just,这里是「设计师工作日常」,今天分享的是使用 css 实现好玩的单行打字机效果,和我一起看看吧。

最新文章通过公众号「设计师工作日常」发布。


目录

整体效果

有趣的css - 打字机动画效果_交互设计

知识点:
animation 动画属性中 steps() 参数的使用
animation 多个 animation-name 的使用

思路:
使宽度从0变为100%,然后利用 steps() 参数使字符一个一个出现,形成打字机效果。


核心代码部分,简要说明了写法思路;完整代码在最后,可直接复制到本地运行。

核心代码

html 代码

<div class="text51">你好,很高兴遇见你!</div>
  • 1.

要显示的文字主体。注意:这里我使用的汉字,一个汉字算2个字符

css 部分代码

.text51{
  width: 0;
  font-weight: bold;
  color: #000;
  white-space: nowrap;
  border-right: 1px solid rgba(0,0,0,0.4);
  animation: texteff51 6s steps(10,start) infinite, lineeff51 0.4s steps(2,start) infinite;
  overflow: hidden;
}
@keyframes texteff51{
  to{
    width: 10rem;
  }
}
@keyframes lineeff51{
  0%{
    border-right: 1px solid rgba(0,0,0,0);
  }
  100%{
    border-right: 1px solid rgba(0,0,0,0.4);
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

1、定义文字主体的样式, white-space: nowrap 让文字不可换行, overflow: hidden 隐藏溢出宽度的内容。

2、定义 texteff51 动画,因为文字主体为10个汉字(包括标点),1个汉字宽度约等于 1 rem,所以这里的关键帧设置 width: 10rem ,然后在 animation 中定义参数 steps(10,start) 让文字内容一个一个出现。

3、定义 lineeff51 动画,让右边框颜色从 rgba(0,0,0,0) 变为 rgba(0,0,0,0.4) 且循环播放,形成光标闪烁效果。

完整代码如下

html 页面

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <title>打字机动画效果</title>
  </head>
  <body>
    <div class="app">
      <div class="text51">你好,很高兴遇见你!</div>
    </div>
  </body>
</html>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

css 样式

/** style.css **/
.app{
  width: 100%;
  height: 100vh;
  background-color: #ffffff;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
.text51{
  width: 0;
  font-weight: bold;
  color: #000;
  white-space: nowrap;
  border-right: 1px solid rgba(0,0,0,0.4);
  animation: texteff51 6s steps(10,start) infinite, lineeff51 0.4s steps(2,start) infinite;
  overflow: hidden;
}
@keyframes texteff51{
  to{
    width: 10rem;
  }
}
@keyframes lineeff51{
  0%{
    border-right: 1px solid rgba(0,0,0,0);
  }
  100%{
    border-right: 1px solid rgba(0,0,0,0.4);
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.

页面渲染效果

有趣的css - 打字机动画效果_交互设计

以上就是所有代码,以及简单的思路,希望对你有一些帮助或者启发。


我是 Just,这里是「设计师工作日常」,求点赞求关注!