如何使用.querySelectorAll使用javascript创建打字机效果?
我希望能够深入了解为什么我的代码不适用于.querySelectorAll,但它适用于getElementById 我最近发现.querySelectorAll传递一个数组,所以我尝试将我制作的代码片段放入for循环,但效果不再有效?我是否有机会了解一下为什么这段代码不能像最初那样“输入” 提前谢谢如何使用.querySelectorAll使用javascript创建打字机效果?,javascript,Javascript,我希望能够深入了解为什么我的代码不适用于.querySelectorAll,但它适用于getElementById 我最近发现.querySelectorAll传递一个数组,所以我尝试将我制作的代码片段放入for循环,但效果不再有效?我是否有机会了解一下为什么这段代码不能像最初那样“输入” 提前谢谢 <!-- HTML --> <div class="style"> <p id="demo" class="type" onclick="
<!-- HTML -->
<div class="style">
<p id="demo" class="type" onclick="typeWriter()">
Click Me
</p>
</div>
//Js global variables
let typewriter = "Write out this sentence";
let speed = 50; //speed in milliseconds
let p = 0; //number of letters in string
//Js with .getElementById
function typeWriter() {
if (p < typewriter.length) {
document.getElementById("demo").innerHTML += typewriter.charAt(p);
p++;
setTimeout(typeWriter, speed);
}
}
//Js with .querySelectorAll
function typeWriter() {
let cycle, i; //establish the cycle and counter
cycle = document.querySelectorAll(".type"); //cycle includes the .type class
for (i = 0; i < cycle.length; i++) { //for loop that actually cycles
while (p < typewriter.length) {
cycle[i].innerHTML += typewriter.charAt(p);
p = p + 1;
setTimeout(typeWriter, speed);
}
}
};
点击我
//Js全局变量
让打字机=“写出这个句子”;
速度=50//以毫秒为单位的速度
设p=0//字符串中的字母数
//带有.getElementById的Js
功能打字机(){
if(p
因为您使用的不是if
,而是while
因此,typewriter.charAt(p)
几乎立即显示,p
几乎立即递增
只需将while
更改为if
,就像使用getElementById
时一样
//Js全局变量
让打字机=“写出这个句子”;
速度=50//以毫秒为单位的速度
设p=0//字符串中的字母数
功能打字机(){
让循环,i;//建立循环和计数器
cycle=document.queryselectoral(“.type”);//cycle包含.type类
for(i=0;i
点击我
因为您使用的不是if
,而是while
因此,typewriter.charAt(p)
几乎立即显示,p
几乎立即递增
只需将while
更改为if
,就像使用getElementById
时一样
//Js全局变量
让打字机=“写出这个句子”;
速度=50//以毫秒为单位的速度
设p=0//字符串中的字母数
功能打字机(){
让循环,i;//建立循环和计数器
cycle=document.queryselectoral(“.type”);//cycle包含.type类
for(i=0;i
点击我
我摆脱了while循环,它似乎可以工作
//Js全局变量
让打字机=“写出这个句子”;
速度=50//以毫秒为单位的速度
设p=0//字符串中的字母数
//带有.getElementById的Js
功能打字机(){
if(p
点击我
我摆脱了while循环,它似乎可以工作
//Js全局变量
让打字机=“写出这个句子”;
速度=50//以毫秒为单位的速度
设p=0//字符串中的字母数
//带有.getElementById的Js
功能打字机(){
if(p
点击我
由于您现在将setTimeout()
函数置于中,而循环嵌套在for
循环中,因此您将在同一秒内设置每个setTimeout
,而不是添加任何延迟。您可以通过在两个loopsAwesome之外调用超时函数来解决此问题,谢谢您的帮助!我想这很有道理。@Sean false。问题不在我