2015-05-06 78 views
0

我想随机化十个容器的背景颜色。使用当前的jQuery,颜色随机加载,但所有容器使用相同的颜色。我将如何改变代码,以在.box元素.box随机列表元素,多个调用

$(document).ready(function(){ 
    var colors = ["#BF2642","#191B29","#366377"];     
    var rand = Math.floor(Math.random()*colors.length);   
    $('.box').css("background-color", colors[rand]); 
}); 

回答

3

只是循环的每个实例单独调用和计算rand为每一个:

$(document).ready(function(){ 
    var colors = ["#BF2642","#191B29","#366377"];     
    $('.box').each(function(){ 
     var rand = Math.floor(Math.random()*colors.length);   
     $(this).css("background-color", colors[rand]); 
    }); 
}); 
相关问题