我想模拟一个自动完成功能。一个句子应该用列表中的单词来完成。这些单词应在句子末尾逐个字符显示。
\n这是 HTML:
\n<p>We can help you with<span id="complete"></span></p>\nRun Code Online (Sandbox Code Playgroud)\n这是 JS 的一部分:
\nlet words = ["design", "frontend", "backend"];\nlet output = document.getElementById("complete");\nRun Code Online (Sandbox Code Playgroud)\n首先我尝试了这个:
\nwords.forEach((e) => {\n for (i = 0; i < e.length; i++) {\n setTimeout(() => {\n console.log(e[i]);\n }, 500);\n }\n});\nRun Code Online (Sandbox Code Playgroud)\n控制台记录:
\n\n我认为这是因为迭代器在setTimeout之前前进。
\n所以我尝试了这样的 while 循环:
\nwords.forEach((e) => {\n let i = 0;\n while (i <= e.length) {\n setTimeout(() => {\n console.log(e[i]);\n }, 600);\n i++;\n }\n});\nRun Code Online (Sandbox Code Playgroud)\n我懂了:
\n\n我不知道如何逐个字符放置 \xe2\x80\x93 ,以便它们加起来等于单词: d; 德;德斯;德西;设计;每个角色之间设计有一定的延迟。
\n(要将单词逐个字符放入 DOM 中,我不会使用控制台日志,而是使用complete.innerHTML += variableForWordinList[index for char])
\n谢谢
\nsetTimeout是异步的。因此,当它执行该函数时,您正在记录的值已经发生了变化。
您想要实现的是一种打字机效果。setInterval它可以通过使用和的组合来实现setTimeout。
let words = ["design", "frontend", "backend"];
let output = document.getElementById("complete");
let idx = 0;
let str = "";
function typeWrite() {
if (idx >= words.length) idx = 0;
let word = words[idx];
let charInd = 0;
let interval = setInterval(() => {
if (charInd >= word.length) {
clearInterval(interval);
setTimeout(() => {
idx++;
str = "";
typeWrite();
}, 1000); // <- Wait for 1 sec before printing next word
}
str += word.charAt(charInd);
output.innerHTML = str;
charInd++;
}, 100); // <- Delay between each character
}
typeWrite();Run Code Online (Sandbox Code Playgroud)
<p>We can help you with <span id="complete"></span></p>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
640 次 |
| 最近记录: |