搜索关键字: Typing Effect
打字效果有各种各样的:
仅实现打字 实现打字与回退 实现多行连续打字 实现任意内容的打字 如果仅仅要实现静态文本打字效果,只用到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 <head > <style > .wrapper { height :100vh ; display : grid; place-items:center; } .typing-demo { width :10ch ; animation : typing 2s steps (5 ), blink .5s step-end infinite alternate; white-space : nowrap; overflow : hidden; border-right : 3px solid; font-family : monospace; font-size : 2em ; } @keyframes typing { from {width :0 ;} } @keyframes blink{ 50% {border-color :transparent;} } </style > </head > <body > <div class ="wrapper" > <div class ="typing-demo" > 打出这行字</div > </div > </body >
比较关键的是用到的字体单位是ch, ch以字体中0为标准,进行相对字体大小设置, 因此总是能将动画卡在每一个字上,而不会有一半字露出来的情况, 纯css的方法一般要将字体数量写死在css里,非常不灵活
自定义内容
通过js获取要显示的文本, 然后通过setTimeout控制字数一点一点增加(删除效果同理,一点一点减少), 很方便能实现文字输入效果:
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 const typingSpeed = 50 , erasingSpeed = 25 let captionLength = 0 const typingInput = document .querySelector ("#test-caption" )const typingBtn = document .querySelector ("#test-typing" )const erasingBtn = document .querySelector ("#test-erasing" )const caption = document .querySelector ("#caption" )const cursor = document .querySelector ("#cursor" )let captionText = "" window .onload = () => { typingBtn.addEventListener ('click' , typing) erasingBtn.addEventListener ('click' , erasing) } function btnControl (enable ){ let fun = enable?'removeAttribute' :'setAttribute' typingBtn[fun]('disabled' ,undefined ) erasingBtn[fun]('disabled' ,undefined ) } function typing ( ){ captionText = typingInput.value if (captionText.length <=0 ) return btnControl (false ) caption.innerHTML = "" let curText = "" cursor.classList .remove ('blink' ) Array .from (captionText).forEach ((ch,index )=> { setTimeout (()=> { curText += ch caption.innerHTML = curText if (index == captionText.length - 1 ){ btnControl (true ) cursor.classList .add ('blink' ) } }, index*typingSpeed) }) } function erasing ( ){ if ( captionText.length <=0 ) return btnControl (false ) cursor.classList .remove ('blink' ) for (let i = captionText.length -1 ; i >= 0 ; i--){ let curText = captionText.slice (0 , i) setTimeout (()=> { caption.innerHTML = curText if (i == 0 ){ btnControl (true ) cursor.classList .add ('blink' ) captionText = '' } },(captionText.length - i)*erasingSpeed) } }