gpt4 book ai didi

javascript - 如何将三种颜色逐一应用于一组div

转载 作者:搜寻专家 更新时间:2023-10-31 23:23:50 25 4
gpt4 key购买 nike

我想应用三种颜色 {red, green, blue} 以便连续分组 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>

关于javascript - 如何将三种颜色逐一应用于一组div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34993375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com