What is the way to change text color letter by letter?
P粉613735289
2023-08-31 13:03:36
<p>I want each letter in the text to change color one by one, one after the other. For example:
Hello World
"H" will turn red first, then "E", then "L", and so on. </p>
<p>I tried wrapping each letter in a span and using jquery and a loop. But it doesn't work. </p>
<p>
<pre class="brush:js;toolbar:false;">$("span").ready(function() {
var letters = $("span").length;
for (let i = 0; i <= letters; i ) {
$("span")[i].css("color", "red");
}
})</pre>
<pre class="brush:html;toolbar:false;"><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> ;</script>
<span>H</span>
<span>E</span>
<span>L</span>
<span>L</span>
<span>O</span>
<span>, </span>
<span>W</span>
<span>O</span>
<span>R</span>
<span>L</span>
<span>D</span></pre>
</p>
You're on the right track, but you need to delay changing the
color
(say100ms
) so the effect can be seen. To delay, we use the method setTimeoutwhich accepts
2 arguments:100ms
).When selecting a delay time, such as
100ms
, we should multiply it by the index of the current letter (the currentspan
to be precise) so that the effect can be seen .This is a live demo:
In jQuery, you can use the
each
function to loop through all elements of the selectorTo "wait" between two color changes, you can embed the CSS changes into the
setTimeout
function, linked to the index of each loop