1、演示
2、实现代码
<!DOCTYPE html> <html lang="ch-ZN"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><style>body {height: 100vh;background: #ffffff;display: flex;justify-content: center;align-items: center;}.container {margin: 0;display: flex;justify-content: center;align-items: center;width: 490px;height: 672px;background-repeat: no-repeat;background-size: cover;position: fixed;}#box {color: rgb(255, 255, 255);padding: 2%;width: 330px;height: 400px;backdrop-filter: blur(4px);-webkit-backdrop-filter: blur(4px);border-radius: 10px;border: 1px solid rgba(255, 255, 255, 0.18);background-color: #000;}</style><script>let textStr ='Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ratione, voluptatibus quos consequatur, quibusdam corrupti quo dolor quisquam quae eveniet voluptas, maxime dicta magnam ipsum rem dignissimos soluta sit consequuntur inventore quaerat! Nemo consectetur quo odio odit sed porro velit distinctio nam. Voluptates in nihil deleniti quia ducimus a vel temporibus.'let strp = ''let i = 0// 实现自动打字效果function print1() {if (textStr[i] != '/') {strp += textStr[i]document.getElementById('box').innerHTML = strp + '|'} else {document.getElementById('box').innerHTML = strp + '<br><br>' + '|'strp += '<br><br>'}i++}function print2() {setTimeout(() => {document.getElementById('box').innerHTML = strp + ' '}, 100)setTimeout(() => {document.getElementById('box').innerHTML = strp + '|'}, 600)}let printid = setInterval(() => {print1()if (i == textStr.length) clearInterval(printid)}, 90)setTimeout(() => {setInterval(print2, 1060)}, (textStr.length - 1) * 90)</script></head><body><div class="container"><div id="box"></div></div></body> </html>
3、实现思路
创建一个空字符串
strp
用于存储逐字打印的文本内容,以及一个计数器i
用于跟踪当前打印到的字符的索引。编写
print1()
函数,该函数负责实现文本的逐字打印效果。在函数内部,通过检查textStr
中的字符来逐个构建strp
字符串,并将其显示在 HTML 页面上的box
元素中。当遇到/
字符时,在box
中添加换行符。编写
print2()
函数,该函数用于模拟光标的闪烁效果。通过两个setTimeout
函数来实现,首先在100毫秒后将光标去除,然后在600毫秒后再次显示光标。使用
setInterval
函数创建一个定时器printid
,在90毫秒的间隔内调用print1()
函数,实现逐字打印的效果。当i
的值等于textStr
的长度时,清除定时器,停止打印。最后,使用
setTimeout
函数在最后一个字符被打印后启动print2()
函数,实现光标闪烁效果。