尝试使用setInterval每秒更改div的背景颜色.jQuery的

jac*_*ank 1 html javascript css jquery

我有一个数组中的颜色列表,我想创建一个遍历数组的函数,并采用与数组的索引相关联的颜色来每秒更改div的背景.div的颜色应该取决于数组索引的位置.

$(document).ready(function(){


var array = ["red", "blue", "yellow"];

var counter = 0;
var nextColor;

function  bgchange() {
    $(".box").css("backgroundColor", "");
    counter = (counter + 1) % array.length;
    nextColor = array[counter];

    $(".box").css("backgroundColor","'" + nextColor +"'");

}


    setInterval(bgchange, 1000)


});
Run Code Online (Sandbox Code Playgroud)

我想通过使用类似于上面的代码但实际上有效的代码来完成此任务.提前谢谢你的帮助.

Ita*_*tay 5

jsFiddle演示

切换backgroundColorbackground-color:

function  bgchange() {
    // $(".box").css("background-color", "");  // Unnecessary command
    counter = (counter + 1) % array.length;
    nextColor = array[counter];

    $(".box").css("background-color", nextColor); // Also no need to wrap
                                                  // variables with quotes

}
Run Code Online (Sandbox Code Playgroud)