gpt4 book ai didi

javascript - 将随机颜色单独应用于类元素?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:49:38 24 4
gpt4 key购买 nike

我的目标是让每个具有“main”类的 div 具有随机背景色。我有生成随机颜色的脚本,但是使用 jquery,我似乎只能将它应用于类中的所有 div。我怎样才能选择一个 div,应用颜色,选择类中的下一个 div,生成一个新的随机颜色,应用它并重复?这是我的代码:

$(document).ready(function() {
var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ','
+ (Math.floor((256-199)*Math.random()) + 200) + ','
+ (Math.floor((256-199)*Math.random()) + 200) + ')';
$('.main').css("background-color", hue);
});

最佳答案

$(document).ready(function() {
$('.main').each(function () {
var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
$(this).css("background-color", hue);
});
});

关于javascript - 将随机颜色单独应用于类元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1535128/

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