jQuery动画背景颜色.删除Math.random

jQuery animate background color. Remove Math.random

本文关键字:Math random 删除 颜色 动画 背景 jQuery      更新时间:2023-09-26

我想在一组背景颜色之间设置动画。

我找到了以下代码,但它使用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);
}); 

因为currentColour是在setInterval函数内声明的,所以您要创建一个新的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);
}); 

问题是您正在初始化代码本身中的"颜色"。

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

您需要定义currentColour函数外的setInterval

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