function output(str) {
const content = document.querySelector('.content')
const child = content.querySelectorAll('.word')
// 删除原有节点
child.forEach(item=>{
content.remove()
})
const arr = [...str]
const blink = document.querySelector('.blink')
// 输出字符
let index = 0
const timer = setInterval(()=>{
if (index == arr.length-1) {
clearInterval(timer)
}
if (arr[index] != '\n') {
const map = {
' ': ' ',
'>': '>',
'<': '<',
}
const text = map[arr[index]] || arr[index]
const span = document.createElement('span')
span.setAttribute('class', `word color${Math.floor(Math.random()*24)}`)
span.innerHTML = text
content.insertBefore(span, blink)
} else {
const br = document.createElement('br')
content.insertBefore(br, blink)
}
index++
}, 200)
}
这样写应该也可以,不知道为什么跑用例不通过= =!

京公网安备 11010502036488号