之前做过一个AI聊天项目,需求之一聊天窗口的消息要以打印效果逐字出现,这样的场景还蛮常见的,记录一下实现过程。 这里自己写了一个js版本的供参考:
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>打印文字效果</title>
<style>
* {
margin: 0;
padding: 0;
}
.container {
width: 540px;
margin: 1em auto;
padding: 1em;
background-color: #000;
border-radius: 5px;
}
p {
line-height: 2;
font-size: 18px;
font-family: 'Courier New', Courier, monospace;
color: peru;
}
</style>
</head>
<body>
<div class="container">
<p></p>
</div>
<script>
const textArr = [
'当你在背单词时,阿拉斯加的鳕鱼正在跃出水面;',
'当你在算数学时,南太平洋的海鸥正掠过海岸;',
'当你在晚自习时,地球的极圈正五彩斑斓;',
'但少年,梦你要亲自实现,世界你要亲自去看。',
'未来可期,拼尽全力!',
'当你为未来付出踏踏实实努力的时候,',
'那么你觉得看不到的人和遇不到的风景都终将在你的生命里出现。'
];
/**
* 延迟函数
*/
function delay(times = 200) {
return new Promise(resolve => setTimeout(resolve, times))
}
async function appendText() {
const p = document.querySelector('p');
let txt = '';
for (const item of textArr) {
txt += `${item}<br/>`;
}
let i = 0;
const len = txt.length;
let html = '';
while(i < len) {
if (txt[i]) {
await delay(100);
if (txt[i] === '<') {
html += '<br/>';
i += 5;
} else {
html += txt[i];
i++;
}
p.innerHTML = html;
}
}
}
appendText();
</script>
</body>
</html>