最近在做个人网站,想实现下面的效果,在网上搜了下,基本都只有打字机效果,没得出现后再删除的效果,于是就自己简单写了个,功能比较简单,详细的描述在注释中都有说明。
效果如下:
html 文本
<h1 id="box"></h1>
css 样式
// keyframes 可根据展示的文本长度,自行添加,我的格式为: @keyframes ‘type’+'文本长度'
@keyframes typing10 {
from {
width: 0;
}
50% {
width: 10ch;
}
100% {
width: 0
}
}
@keyframes typing4 {
from {
width: 0;
}
50% {
width: 4ch;
}
100% {
width: 0
}
}
@keyframes typing6 {
from {
width: 0;
}
50% {
width: 6ch;
}
100% {
width: 0
}
}
@keyframes caret { 50% { border-color: transparent; } }
h1 {
width: 0;
animation: typing 6s steps(15) infinite,caret 1s steps(1) infinite;
white-space: nowrap;
overflow:hidden;
border-right: .05em solid;
font-family: Consolas, Monaco, monospace;//注意这儿,要设置字体为等宽字体,ch才会充分发挥效果
}
js文件
const arr = ['TypeScript','JavaScript','小程序','less','sass' ];//显示的文本
const dom = document.getElementById('box')
let j = 0; //从数组第一个开始展示
// 递归函数
const func =(j) => {
if(j < arr.length){ // 当达到数组长度时,就从头开始继续
const item = arr[j]
const itemLen = item === '小程序' ? 6 : item.length; // 汉字是占两个ch
dom.innerHTML = item; // 显示文字
for (var i = 0, len = itemLen; i < len; i++) { // 添加文本效果
var textLen = dom.textContent.length, s = dom.style;
s.animationTimingFunction = "steps(" + textLen + "),steps(1)";; //动态设置steps
s.animationName = `typing${itemLen}`; //文本长度不同,展示的宽度就不同,所以需要动态设置
s.animationDuration = `${itemLen/2}s,0.5s`; //这儿设置速度
}
setTimeout(() => {
func(j + 1)
},itemLen*500) //这儿和上面的animationDuration速度一致,只不过这儿是毫秒,所以要乘以1000
}else{
func(0); //就从头开始继续
}
}
func(j);
参考文章: https://www.w3cplus.com/css3/css-secrets/typing-animation.html