我想制作一个简单的聊天机器人。它应该能够一个接一个地写多行。我的问题是,我无法弄清楚如何使它们不是同时出现,而是在另一个之后出现(可能在两者之间有延迟使其更加真实)。
相关问题: Show text letter by letter
尝试过的代码: http://jsfiddle.net/VZvK7/1447/
<div id="msg"/>
<span id="text_target"></span></div>
<div id="msg2"/>
<span id="text_target"></span></div>
<div id="msg3"/>
<span id="text_target"></span></div>
var showText = function (target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () { showText(target, message, index, interval); }, interval);
}
}
$(function () {
showText("#msg", "Hello, World!", 0, 500);
showText("#msg2", "Hello, World!", 0, 500);
showText("#msg3", "Hello, World!", 0, 500);
});
答案 0 :(得分:0)
你可以试试这个:
const printMessage = (target, message, frequency) => {
message.forEach((line, lineIndex) => {
const baseInterval = message.slice(0, lineIndex).join(' ').length * frequency
line.split('').forEach((character, charIndex) => {
const t = setTimeout(() => {
target.innerHTML = `${target.innerHTML}${character}${charIndex === line.length - 1 ? '<br/>' : ''}`
clearTimeout(t)
}, baseInterval + charIndex * frequency)
})
})
}
const target = document.getElementById('target')
printMessage(target, [
'Hello World!',
'How are you ?'
], 100)
JSFiddle:http://jsfiddle.net/VZvK7/1452/