HTML+CSS实现打字机效果

想要实现文字打字机的效果可以有很多方式,今天分享的是使用css的方式来实现这个效果

首先准备一个html文件,并准备要实现打字机效果的文字

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>打字机</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    body {
      display: flex;
      height: 100vh;
      justify-content: center;
      align-items: center;
      background-color: #454545;
      font-size: 10px;
      color: #fff;
    }
    h1 {
      position: relative;
      font-weight: 400;
    }
  </style>
</head>
<body>
  <h1 class="heading">This is a paragraph</h1>
</body>
</html>

效果如下

给文字添加伪类元素的绝对定位

h1::before, h1::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

通过after伪类元素在文字上方添加背景颜色覆盖文字, 并添加动画效果即可实现文字逐个出现的效果

h1::before{
  background-color: red;
  animation: typing 2s forwards;
}

@keyframes typing {
  to {
    left: 100%;
  }
}

打字标实现的原理是通过after伪类元素进行实现

h1::after {
  width: 2px;
  background-color: #fff;
  animation: typing 2s forwards;
}

实现效果如下

可以看到已经出现为文字随着打字标逐个出现的效果了,此时只要将before属性的背景颜色修改为文字的背景颜色即可

h1::before {
  background-color: #454545;
  animation: typing 2s forwards;
}

可以通过animation的steps属性来实现文字停顿出现文字的效果

h1::before {
  background-color: #454545;
  animation: typing 4s steps(19) forwards;
}
h1::after {
  width: 2px;
  background-color: #fff;
  animation: typing 4s steps(19) forwards;
}

实现效果如下

 此时已经完整的文字打印机效果了,完整代码如下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>打字机</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    body {
      display: flex;
      height: 100vh;
      justify-content: center;
      align-items: center;
      background-color: #454545;
      font-size: 10px;
      color: #fff;
    }
    h1 {
      position: relative;
      font-weight: 400;
    }

    h1::before, h1::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }
    h1::before {
      background-color: #454545;
      animation: typing 4s steps(19) forwards;
    }
    h1::after {
      width: 2px;
      background-color: #fff;
      animation: typing 4s steps(19) forwards;
    }
    @keyframes typing {
      to {
        left: 100%;
      }
    }
  </style>
</head>
<body>
  <h1 class="heading">This is a paragraph</h1>
</body>
</html>

感谢收看,如果对你有帮助的话请点赞收藏!

  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值