繁体   English   中英

JavaScript 打字效果 Function

[英]JavaScript Typing Effect Function

我正在尝试编写一个 JS function,它接受一个参数,txt 并逐个字母打印,我已经有一个代码,但是当我尝试将它“转换”为 function 时它停止工作。 有任何想法吗?

 var myText = "Text to be displayed"; var myArray = myText.split(""); var loopTimer; function frameLooper() { if(myArray.length > 0) { document.getElementById("type_text").innerHTML += myArray.shift(); } else { clearTimeout(loopTimer); return false; } loopTimer = setTimeout("frameLooper()",70); } frameLooper();

打字效果function:

 var i; var speed = 120; function typeWriter(txt) { for (i=0;i<=txt.length - 1;i++) { document.getElementById("type_text").innerHTML += txt.charAt(i); setTimeout(typeWriter, speed); } } typeWriter("text to be typed");

您需要将原始文本传递给setTimeout中的 function ,并删除您在每个setTimeout回调中调用的整个文本的循环(这使得它在每个回调中打印整个文本)。

作为增强,我建议在 function 调用中传递索引。

 const SPEED = 120; function typeWriter(txt, i = 0) { document.getElementById("type_text").innerHTML += txt.charAt(i); // check if the entire text has been typed if (i < txt.length - 1) { // pass function with the text and the index (+1) setTimeout(() => typeWriter(txt, i + 1), SPEED); } } typeWriter("text to be typed");
 <p id="type_text"></p>

使用 promises 和async更容易:

 let delay = n => new Promise(r => setTimeout(r, n)); async function typeWriter(div, txt) { for (let char of txt) { div.innerHTML += char; await delay(200); } } typeWriter(document.querySelector('#type'), 'hello there')
 <div id="type"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM