我想应用三种颜色{红色,绿色,蓝色}以连续组成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>
答案 0 :(得分:4)
您当前的逻辑存在缺陷,因为框的索引将超过阵列中可用的类数。要解决此问题,您可以使用模运算符%
。试试这个:
$(document).ready(function(e) {
var colors = ["red", "green", "blue"];
$('.box').each(function(i) {
$(this).addClass(colors[i % colors.length]);
});
});
&#13;
.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;
}
&#13;
<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>
&#13;
另请注意,使用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;
}
&#13;
<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>
&#13;