What is the way to change text color letter by letter?
P粉613735289
P粉613735289 2023-08-31 13:03:36
0
2
639
<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>
P粉613735289
P粉613735289

reply all(2)
P粉521013123

You're on the right track, but you need to delay changing the color (say 100ms) so the effect can be seen. To delay, we use the method setTimeout which accepts 2 arguments:

  1. A callback function that is called after the required delay time has passed.
  2. The required delay time (such as 100ms).

When selecting a delay time, such as 100ms, we should multiply it by the index of the current letter (the current span to 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))
<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>
P粉865900994

In jQuery, you can use the each function to loop through all elements of the selector

To "wait" between two color changes, you can embed the CSS changes into the setTimeout function, linked to the index of each loop

$(".letters span").each(function(index, elem) {
  setTimeout(function() {
    $(elem).css('color', 'red');
  }, index * 500);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="letters">
  <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>
</div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!