2016-07-26 253 views
1

我想在背景颜色数组之间进行动画处理。jQuery动画背景颜色。删除Math.random

我发现下面的代码,但它使用Math.random以随机顺序显示背景颜色。

$(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); 
}); 

JSFiddle

我想删除的Math.random和显示阵列中的下一个颜色。

但是,如果我使用以下代码替换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); 
}); 

回答

1

因为currentColoursetInterval函数内声明的,要创建一个新的currentColour变量,它的每一个函数被调用时设置为0。相反,移动currentColour功能范围之外:

$(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); 
}); 
0

的问题是在代码本身你重新初始化“theColour”。

$(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); 
}); 
0

您需要定义currentColour输出功能的setInterval的

$(document).ready(function() { 
 
\t \t 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); 
 
});