我在一个页面上有六个 div,每个都有相同的类。我正在尝试为它们中的每一个分配一种我在数组中选择的独特颜色。我不希望它们中的任何一个具有相同的颜色。
我已经成功地从一个数组中为每个 div 分配了背景颜色,但是,一些类可以获得相同的背景颜色,因为它目前只是从数组中随机选择颜色。
jQuery(document).ready(function($) {
$(".et_pb_post").each(function() {
var colors = ["#CFEAEA ","#c9e3d5","#e7dadd","#dde9eb","#ecfac7","#facba9","#dfdbd3","#f1fdc1"];
var rand = Math.floor(Math.random()*colors.length);
$(this).css("background-color", colors[rand]);
});
});
然后 html 是这样的
<div class="et_pb_post">Some content with bg-color A</div>
<div class="et_pb_post">Some content with bg-color B</div>
<div class="et_pb_post">Some content with bg-color C</div>
<div class="et_pb_post">Some content with bg-color D</div>
如何确保所有背景颜色都是唯一的?
非常感谢!
最佳答案
您可以这样做的一种方法是创建颜色数组的副本,并在为 div 选择时从中删除颜色:
jQuery(document).ready(function($) {
var colors = ["#CFEAEA ", "#c9e3d5", "#e7dadd", "#dde9eb", "#ecfac7", "#facba9", "#dfdbd3", "#f1fdc1"];
var copy = [...colors];
$(".et_pb_post").each(function() {
var rand = Math.floor(Math.random() * copy.length);
$(this).css("background-color", copy[rand]);
copy = copy.filter(color => color !== copy[rand]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="et_pb_post">Some content with bg-color A</div>
<div class="et_pb_post">Some content with bg-color B</div>
<div class="et_pb_post">Some content with bg-color C</div>
<div class="et_pb_post">Some content with bg-color D</div>
关于javascript - 将背景颜色分配给数组中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57097281/