看见一个不错的特效:
效果如下:
html 文本
css 样式
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 33 34 35 36 37 38 39 40 41 42 43 44
| // 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文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| 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; 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)";; 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