[英]How To Create a Typewriter effect with javascript using .querySelectorAll?
希望我能深入了解为什么我的代码不适用于.querySelectorAll 但它适用于getElementById?
我最近发现 .querySelectorAll 传递了一个数组,所以我尝试将我制作的这段代码片段放入 for 循环中,效果不再有效? 我有没有机会了解为什么这段代码没有像原来那样“打字”?
提前致谢!
<!-- 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);
}
}
};
因为您使用的是while
不是if
。
因此, typewriter.charAt(p)
将几乎立即显示,并且p
几乎立即递增。
只需将while
更改为if
就像您在使用getElementById
时所做的那样。
//Js global variables let typewriter = "Write out this sentence"; let speed = 50; //speed in milliseconds let p = 0; //number of letters in string 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 if (p < typewriter.length) { cycle[i].innerHTML += typewriter.charAt(p); p = p + 1; setTimeout(typeWriter, speed); } } };
<div class="style"> <p id="demo" class="type" onclick="typeWriter()"> Click Me </p> </div>
我摆脱了while循环,它似乎工作
//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 cycle[i].innerHTML += typewriter.charAt(p); p =p + 1; setTimeout(typeWriter, speed) } };
<!-- HTML --> <div class="style"> <p id="demo" class="type" onclick="typeWriter()"> Click Me </p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.