想要实现文字打字机的效果可以有很多方式,今天分享的是使用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>
感谢收看,如果对你有帮助的话请点赞收藏!