[英]changing color of different spans one after another
I have some text and I want it to change color in a manner such that the left alphabet changes color first, then the next one and so on(like a wave). 我有一些文字,我希望它以一种方式改变颜色,使得左字母首先改变颜色,然后改变下一个等等(如波浪)。 So, I assigned each alphabet a span(with class span0, span1 and so on) and tried changing the color using following code: 所以,我为每个字母分配了一个跨度(类span0,span1等)并尝试使用以下代码更改颜色:
for (var i = 0; i < spans.length; i++) {
window.setTimeout(function(){
$(".span"+i).animate({'color':'orange'}, 400);
}, 300);
};
The code doesn't work. 代码不起作用。 (and I am using the jQuery color plugin) So, how can I achieve the effect? (我使用的是jQuery颜色插件)那么,我该如何实现这个效果呢?
This is the classic "using a loop variable inside a callback bug" - by the time the callback is invoked the value of i
is set to its last known value instead of the value it had at the time the callback was registered. 这是经典的“在回调错误中使用循环变量” - 在调用回调时, i
的值被设置为其最后的已知值,而不是回调注册时的值。
Try this: 尝试这个:
// _returns_ a new function that's bound to the specified selector
function setcolor(sel) {
return function() {
$(sel).animate({'color', 'orange'}, 400);
}
}
// set the callback to the function returned above
for (var i = 0; i < spans.length; ++i) {
window.setTimeout(setcolor('.spans' + i), 300 + 400 * i);
}
per @cwolves answer - you also need to stagger the timeouts otherwise they'll all fire at once, hence the 300 + 400 * i
in the code above. 根据@cwolves的回答 - 你还需要错开超时,否则它们会立刻发射,因此上面代码中的300 + 400 * i
。
for( var i = 0; i < spans.length; i++ ){
$( '.span' + i ).delay( 300 + i*50 ).animate( {'color':'orange'}, 400 );
}
Using jQuery, delay for an increasing amount of time then animate the color switch. 使用jQuery,延迟一段时间,然后为颜色开关设置动画。 You have two issues -- You're firing all the animations at the same time, and as Alnitak points out -- your i
variable isn't in the proper scope 你有两个问题 - 你正在同时解雇所有的动画,正如Alnitak指出的那样 - 你的i
变量不在适当的范围内
And you can also remove the need for .span0
, .span1
, etc by giving them all a span
class and changing the selector in the above code to: 您还可以通过为它们提供所有span
类并将上面代码中的选择器更改为以下.span0
来删除对.span0
, .span1
等的需要:
var $spans = $( '.span' )
for( ... ){
$spans.eq( i )...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.