如何将三种颜色一一应用于一组 div 的连续



我想应用三种颜色,即{红色,绿色,蓝色},以便对div进行连续分组。我使用带有"for"循环的数组将颜色应用于div,但它无法正常工作。

我的代码是:

$(document).ready(function(e) {
  var colors = ["red", "green", "blue"];
  var len = $('.box').length;
  for (var j = 0; j < len; j++) {
    $(this).find('.box').addClass(colors[j]);
  }
});
.red {
  background-color: red;
}
.green {
  background-color: green;
}
.blue {
  background-color: blue;
}
.box {
  float: left;
  height: 50px;
  margin-left: 5px;
  margin-top: 10px;
  width: 50px;
  border: 1px solid #000;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>demo</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</body>
</html>

您当前的逻辑存在缺陷,因为框的索引将超过数组中可用的类数。要解决此问题,您可以使用取模运算符 % 。试试这个:

$(document).ready(function(e) {
  var colors = ["red", "green", "blue"];
  $('.box').each(function(i) {
    $(this).addClass(colors[i % colors.length]);
  });
});
.red {
  background-color: red;
}
.green {
  background-color: green;
}
.blue {
  background-color: blue;
}
.box {
  float: left;
  height: 50px;
  margin-left: 5px;
  margin-top: 10px;
  width: 50px;
  border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

另请注意,单独使用 CSS 和 nth-child 选择器可以实现完全相同的效果:

.box:nth-child(3n+1) {
  background-color: red;
}
.box:nth-child(3n+2) {
  background-color: green;
}
.box:nth-child(3n) {
  background-color: blue;
}
.box {
  float: left;
  height: 50px;
  margin-left: 5px;
  margin-top: 10px;
  width: 50px;
  border: 1px solid #000;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

最新更新