gpt4 book ai didi

javascript - 如何把这个函数变成干函数?

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:13 25 4
gpt4 key购买 nike

我正在尝试向我的页面添加打字机效果,它可以很好地处理预定义数据,但我无法将其转换为接收值然后打印这些值的函数。

我尝试通过添加参数来更改原始函数并尝试打印传入的值,但只打印了第一个字母。

<-- 这是原始函数。 -->

let i = 0;
let txt = 'Hello world';
let speed = 50;

function typeWriter() {
if (i < txt.length) {
document.getElementById("text").innerHTML +=
txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}

typeWriter();

<-- 这是我把它改成的。 -->

function typeWriter(id, text) {
if (i < text.length) {
document.getElementById(id).innerHTML += text.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}


typeWriter("text", "Hello world" );

打印第一个字母,控制台打印这条消息“error”“类型错误:无法读取未定义的属性‘长度’ 在 typeWriter (xifoxoj.js:18:16)”

我的预期值是传递给函数的文本值将完全打印在带有传递给函数的 id 的元素中,而不是只打印文本值的第一个字母。

最佳答案

使用 String#split、Array#forEach。

注意:按speed * i增加速度

function typeWriter(id, text) {
const speed = 500;
const ele = document.getElementById(id)
text.split("").forEach((c,i)=>{
setTimeout(()=>{
ele.innerHTML += c;
}, speed*i);
});
}


typeWriter("text", "Hello world");
<div id="text"></div>

关于javascript - 如何把这个函数变成干函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54344309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com