每个元素的颜色随机

时间:2019-08-05 08:02:20

标签: javascript jquery

我想使容器中的每个元素都具有从数组中随机选择的不同背景色。如何让脚本针对每个新元素分别运行?

$(document).ready(function(){
  var colors = ["#ff0000","#ff00ff","#00ff00"];                
  var rand = Math.floor(Math.random()*colors.length);           
  $('.resource-cards > div').css("background-color", colors[rand]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="resource-cards">
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
</div>

3 个答案:

答案 0 :(得分:5)

您可以使用each遍历每个div并分配随机颜色。

$(document).ready(function() {

  $('.resource-cards > div').each(function() {
    var colors = ["#ff0000", "#ff00ff", "#00ff00"];
    var rand = Math.floor(Math.random() * colors.length);
    $(this).css("background-color", colors[rand]);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="resource-cards">
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
</div>

答案 1 :(得分:3)

要使每个元素单独工作,您需要遍历div元素并为每个元素生成一个随机数,如下所示:

$(document).ready(function() {
  var colors = ["#ff0000", "#ff00ff", "#00ff00"];

  $('.resource-cards > div').each(function() {
    var rand = Math.floor(Math.random() * colors.length);
    $(this).css("background-color", colors[rand]);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="resource-cards">
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
  <div>some text</div>
</div>

答案 2 :(得分:1)

从数组中随机选择的容器的不同背景颜色。

使用循环概念。

$(document).ready(function() {

  $('.resource-cards > div').each(function() {
    var colorsArray = ["#338DFF","#ff0000", "#ff00ff", "#00ff00","#FF5733"];
    var randnum = Math.floor(Math.random() * colorsArray.length);
    $(this).css("background-color", colorsArray[randnum]);
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="resource-cards">
  <div>DIV 1</div>
  <div>DIV 2</div>
  <div>DIV 3</div>
  <div>DIV 4</div>
  <div>DIV 5</div>
</div>