我正在尝试更改文本的颜色并设置超时。 就像每 5 秒颜色就会改变一次。 我就是无法让它发挥作用。我做错了什么?
var rainBowColors = new Array();
rainBowColors.push("#FF0000"); //Red: #FF0000
rainBowColors.push("#FF7F00"); //Orange: #FF7F00
rainBowColors.push("#FFFF00"); //Yellow: #FFFF00
rainBowColors.push("#00FF00"); //Green: #00FF00
rainBowColors.push("#0000FF"); //Blue: #0000FF
rainBowColors.push("#4B0082"); //Indigo: #4B0082
rainBowColors.push("#8F00FF"); //Violet: #8F00FF
var rainbowCounter = 0;
for (var counter = 0; counter < 1000; counter++)
{
//Easter :)
//var timeOut = setTimeOut(function(){
jQuery(".text").css("color", rainBowColors[rainbowCounter]);
//}, 500);
//clearTimeOut(timeOut);
//Higher Counter
rainbowCounter++;
//Reset counter
if (rainbowCounter == rainBowColors.length)
{
rainbowCounter = 0;
}
}
最佳答案
回答你的问题:在你的代码中,颜色确实会改变,只是为了让眼睛快速看到。该循环以非常快的速度运行所有 1000 次迭代,其中每次迭代都会执行超时(也非常快),这反过来又使它们看起来几乎同时解析(太快了,肉眼无法看到)。最重要的是,如果以这种方式触发,您的计时器由于其异步性质而并行滴答作响,您需要的是计时器按顺序启动,一个接一个。希望这是有道理的
尝试使用 setInterval 而不是超时
var rainBowColors = new Array();
rainBowColors.push("#FF0000"); //Red: #FF0000
rainBowColors.push("#FF7F00"); //Orange: #FF7F00
rainBowColors.push("#FFFF00"); //Yellow: #FFFF00
rainBowColors.push("#00FF00"); //Green: #00FF00
rainBowColors.push("#0000FF"); //Blue: #0000FF
rainBowColors.push("#4B0082"); //Indigo: #4B0082
rainBowColors.push("#8F00FF"); //Violet: #8F00FF
var rainbowCounter = 0;
var interval = setInterval(function(){
jQuery(".text").css("color", rainBowColors[rainbowCounter]);
rainbowCounter++;
//Reset counter
if (rainbowCounter == rainBowColors.length)
{
rainbowCounter = 0;
}
},100);
附注这个数组声明与您的相同,但更简洁一些。您可能想使用它:
var rainBowColors = [
"#FF0000", //Red
"#FF7F00", //Orange
"#FFFF00" //Yellow
// ... add other colors
];
关于javascript - 延迟切换文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19270602/