gpt4 book ai didi

javascript - 每个元素的随机颜色

转载 作者:行者123 更新时间:2023-11-30 07:12:07 26 4
gpt4 key购买 nike

我想让容器中的每个元素都具有从数组中随机选择的不同背景颜色。如何让脚本针对每个新元素单独运行?

$(document).ready(function(){
var colors = ["#ff0000","#ff00ff","#00ff00"];
var rand = Math.floor(Math.random()*colors.length);
$('.resource-cards > div').css("background-color", colors[rand]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="resource-cards">
<div>some text</div>
<div>some text</div>
<div>some text</div>
<div>some text</div>
<div>some text</div>
<div>some text</div>
</div>

最佳答案

您可以使用 each遍历每个 div 并分配随机颜色。

$(document).ready(function() {

$('.resource-cards > div').each(function() {
var colors = ["#ff0000", "#ff00ff", "#00ff00"];
var rand = Math.floor(Math.random() * colors.length);
$(this).css("background-color", colors[rand]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="resource-cards">
<div>some text</div>
<div>some text</div>
<div>some text</div>
<div>some text</div>
<div>some text</div>
<div>some text</div>
</div>

关于javascript - 每个元素的随机颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57354472/

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