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 accepts2 arguments:100ms).When selecting a delay time, such as
100ms, we should multiply it by the index of the current letter (the currentspanto be precise) so that the effect can be seen .This is a live demo:
/** * 循环遍历“span”元素。 * 延迟100ms * i(当前span索引),以便稍后改变索引为“i”的span的颜色。 * 你可以根据需要更改延迟时间(在这个例子中是100)。 */ $('span').each((i, el) => setTimeout(() => $(el).css('color', 'red'), i * 100))In jQuery, you can use the
eachfunction to loop through all elements of the selectorTo "wait" between two color changes, you can embed the CSS changes into the
setTimeoutfunction, linked to the index of each loop$(".letters span").each(function(index, elem) { setTimeout(function() { $(elem).css('color', 'red'); }, index * 500); });