2015-04-03 77 views
1

使用下面的代码目前分配随机背景颜色:更改随机jQuery的背景颜色重复顺序?

// Add random background color to tiles 
var colors = ["#F2B036","#10AF70","#2A82AF","#68B0BB", "#6B7889"]; 
var rand = function() { 
       return Math.floor(Math.random()*5); 
      }; 
var randomColor = function() { 
        var x = colors[rand()]; 
        return x; 
      }; 

$(".ThumbnailMenuItem").each(function() { 
    $(this).css("background-color", randomColor()); 
}); 

不过,我不希望这是随机的,因为它的颜色会时而出现紧挨彼此。

我如何调整这个,以便它使用的颜色排列顺序,但在零位重新开始,如果有更多的ThumbnailMenuItem班比在阵列中的颜色?

回答

3

您可以简单地用一个计数器和更新。

var i = 0; 
$(".ThumbnailMenuItem").each(function() { 
    $(this).css("background-color", colors[i++]); // increment here 
    if(i == 5) i = 0; // reset the counter here 
}); 
+0

将'$(本)的CSS( “背景颜色”,颜色[I ++]);'开始在'颜色[1]',代替'颜色[0]'? – guest271314 2015-04-03 14:54:29

+1

@ guest271314没有。由于我使用了后缀增量运算符,因此它将从'0开始。 '颜色[i ++]'起初将是'colors [0]',但是当评估条件时,它将是'1' – 2015-04-03 14:55:44

1

我建议:

var colors = ["#F2B036","#10AF70","#2A82AF","#68B0BB", "#6B7889"]; 
 

 
// iterating over each of the elements returned by the selector, 
 
// with the css() method, using the first argument (the index 
 
// of the current element in the collection) of the anonymous function: 
 
$(".ThumbnailMenuItem").css("background-color", function (index) { 
 
    // returning the modulus of the index against the length 
 
    // of the array of colours: 
 
    return colors[index%colors.length]; 
 
});
li { 
 
    height: 1em; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li class="ThumbnailMenuItem"></li> 
 
    <li class="ThumbnailMenuItem"></li> 
 
    <li class="ThumbnailMenuItem"></li> 
 
    <li class="ThumbnailMenuItem"></li> 
 
    <li class="ThumbnailMenuItem"></li> 
 
    <li class="ThumbnailMenuItem"></li> 
 
    <li class="ThumbnailMenuItem"></li> 
 
    <li class="ThumbnailMenuItem"></li> 
 
    <li class="ThumbnailMenuItem"></li> 
 
    <li class="ThumbnailMenuItem"></li> 
 
</ul>

参考文献: