如何将三种颜色依次应用于一组 div 中,串行方式

3

我希望能够对一组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>


1
为什么不使用 CSS 选择器而不是 jQuery/JS 来完成这件事? - Harry
颜色数组中的元素比盒子数组中的元素少... - neuhaus
1个回答

4

您当前的逻辑存在缺陷,因为盒子的索引将超过数组中可用的类数。为了解决这个问题,您可以使用模运算符%。请尝试以下方法:

$(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>

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

.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>


刚刚看到了 nth-child,于是我删除了重复的答案。 - Tushar
@Muthupandianc 没问题,很高兴能帮助。 - Rory McCrossan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接