P粉5210131232023-09-01 10:14:21
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:
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粉8659009942023-09-01 00:21:23
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>