demo代码:
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>打字机</title><style>.text {font-size: 40px;}.content {text-align: center;font-size: 0;}.blink {font-size: 40px;animation: tiaodong 1000ms infinite;-webkit-animation: tiaodong 1000ms infinite;}@keyframes tiaodong {from {opacity: 1;}50% {opacity: 0;}to {opacity: 1;}}</style>
</head><body><div class="content"><span class="blink" id='blink'>|</span></div>
</body>
<script>function output(str) {const content = document.getElementsByClassName('content')[0]const blink = document.getElementById('blink');let i = 0const stI = setInterval(() => {if (str[i] === '\n') {const br = document.createElement('br');content.insertBefore(br, blink)} else {const span = document.createElement('span');span.classList.add('text')switch (str[i]) {case " ":span.innerHTML = ' 'break;case '<':span.innerHTML = '<'break;case '>':span.innerHTML = '>'break;default:span.innerHTML = str[i]break;}content.insertBefore(span, blink)}i++;if (i >= str.length) {clearInterval(stI)}}, 200)}output('你好,我是你的智能机器人ChartGPT\n有什么可以帮你的吗?')
</script></html>
效果如下: