CSS实现打字机效果的方法
墨初 Web前端 1276阅读
在我们不使用javascript脚本的情况下,可以通过CSS样式表中的一些小技巧来实现输出文字时实现打字机的效果。下面是具体的使用示例,大家可以参考一下。
HTML CSS实现打字机效果
例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body {
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.type-writer .text {
width: 43ch;
animation: typing 2s steps(22), blink .5s step-end infinite alternate;
white-space: nowrap;
overflow: hidden;
border-right: 3px solid;
font-family: monospace;
font-size: 1.5em;
margin: 1em auto;
}
@keyframes typing {
from {
width: 0
}
}
@keyframes blink {
50% {
border-color: transparent
}
}
</style>
<body>
<div>
<div>All work and no play makes Jack a dull boy!</div>
</div>
</body>
</html>注:
1、white-space: nowrap 和 overflow: hidden 来隐藏溢出字符,定义等宽字体以使容器的宽度可预测,
2、设置周围容器宽度的动画。闪烁的光标通过设置右边框的动画来实现。
3、定义两个动画,typing 以设置角色动画和 blink 动画插入符号。