将随机jquery背景颜色更改为重复顺序?

时间:2015-04-03 14:46:34

标签: jquery css

目前使用以下代码分配随机背景颜色:

 // 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类多于数组中的颜色,则从零位开始?

2 个答案:

答案 0 :(得分:3)

您只需使用计数器并进行更新即可。

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

答案 1 :(得分: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>

参考文献: