Javascript jQuery动画背景颜色。删除Math.random
我想在背景色数组之间设置动画 我找到了以下代码,但它使用Math.random以随机顺序显示背景色Javascript jQuery动画背景颜色。删除Math.random,javascript,jquery,html,css,random,Javascript,Jquery,Html,Css,Random,我想在背景色数组之间设置动画 我找到了以下代码,但它使用Math.random以随机顺序显示背景色 $(document).ready(function() { setInterval(function() { var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff'); var theColour = theColours[Math.floor(Math.rand
$(document).ready(function() {
setInterval(function() {
var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
var theColour = theColours[Math.floor(Math.random()*theColours.length)];
$('#branding').animate({backgroundColor: theColour}, 500);
}, 1000);
});
我想删除Math.random并显示数组中的下一种颜色
$(document).ready(function() {
setInterval(function() {
var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
var currentColour = 0;
var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
$('#branding').animate({backgroundColor: theColour}, 500);
}, 1000);
});
但是,如果我用以下内容替换Math.random,则动画将不会超过数组中的第一种颜色
$(document).ready(function() {
setInterval(function() {
var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
var currentColour = 0;
var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
$('#branding').animate({backgroundColor: theColour}, 500);
}, 1000);
});
由于
currentColour
是在setInterval
函数中声明的,因此每次调用该函数时,都要创建一个新的currentColour
变量并将其设置为0
。将CurrentColor
移到功能范围之外:
$(document).ready(function() {
var currentColour = 0; // This variable is now shared by each function call
setInterval(function() {
var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
$('#branding').animate({backgroundColor: theColour}, 500);
}, 1000);
});
问题是您正在初始化代码本身中的“颜色”
$(document).ready(function() {
var currentColour = 0;
setInterval(function() {
var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
$('#branding').animate({backgroundColor: theColour}, 500);
}, 1000);
});
您需要定义函数外设置间隔的CurrentColor
$(文档).ready(函数(){
var CurrentColor=0;
setInterval(函数(){
变量颜色=数组('ffffff'、'000000'、'00ff00'、'ff0000'、'0000ff');
颜色变量=颜色[数学地板(当前颜色+++%颜色长度)];
$(#branding').animate({backgroundColor:thecolor},500);
}, 1000);
}); 代码>