基于JavaScript實現(xiàn)驚艷的打字機效果
先準備一個Html的模版:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body { background-color: black; color: white; } #switch-box { color: #0cc4fb; } </style> </head> <body> 我要成為 <span id="switch-box"></span> 高手 </body> </html>
在switch-box中實現(xiàn)打字效果,得利用js,首先定義一個字符串數組,用于在打字機中切換文字,然后定義一個函數將數組中的字放到內容中,每次切換后索引+1,然后循環(huán)調用這個函數,當索引大于數組長度的時候,把索引重新歸0
const stringArray = ['C++','Go','Java','Js','PHP'] let switch_box = document.getElementById('switch-box') // 定義數組索引 let index = 0 let delay = 500 let changeText = () => { switch_box.textContent = stringArray[index] index ++ if(index >= stringArray.length){ index = 0 } setTimeout(changeText,delay) } changeText()
這其實已經能實現(xiàn)切換了,只是沒有打字效果,我們再利用js,用于顯示一個個字符的顯示,利用substring切割字符,每次字符數量+1,當切割全部的時候,就該執(zhí)行刪除了,所以應該定義一個刪除的標志,在刪除完之后,就應該切換到下一個字符了。
下面是完整代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body { background-color: black; color: white; } #switch-box { color: #0cc4fb; } </style> </head> <body> 我要成為 <span id="switch-box"></span> 高手 <script> const stringArray = ['C++','Go','Java','Js','PHP'] let switch_box = document.getElementById('switch-box') // 定義數組索引 let index = 0 let delay = 0 let charIndex = 0 // 刪除標志 let isDelete = false let defaultDelay = 300 let waitDalay = 1000 let changeText = () => { switch_box.textContent = stringArray[index].substring(0,charIndex); if(!isDelete){ delay = defaultDelay charIndex ++ if(charIndex > stringArray[index].length){ // 當charIndex已經大于字符的長度的時候,表示應該執(zhí)行刪除動畫了 isDelete = true delay = waitDalay } }else{ delay = defaultDelay charIndex -- if(charIndex < 1){ isDelete = false index ++ if(index >= stringArray.length){ index = 0 } } } setTimeout(changeText,delay) } changeText() </script> </body> </html>
最后補充下文字后的光標閃爍效果
/*打字樣式光標*/ #switch-box::after { content: "I"; font-size: 18px; display: inline-block; vertical-align: top; font-weight: lighter; animation: flicker .5s infinite; } /*光標閃爍動畫*/ @keyframes flicker { 0% { opacity: 0; } 100% { opacity: 1; } }
效果圖
到此這篇關于基于JavaScript實現(xiàn)驚艷的打字機效果的文章就介紹到這了,更多相關JavaScript打字機內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
微信小程序實現(xiàn)動態(tài)渲染Markdown示例詳解
這篇文章主要為大家介紹了微信小程序實現(xiàn)動態(tài)渲染Markdown示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08