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

3
我的目标是为所有class为“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);
});
3个回答

21
$(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);
    });
});

完美,但我有一个问题。有没有办法只显示深色?它一直显示浅色。请帮忙。 - Amit Rana

2
代码应该是这样的...
$(document).ready(function() {
                        $('.main').each{ Function(){
                             $(this).css("background-color", hue); };
                        };
                });

对于犯错误的事情我很抱歉。修正了那些最严重的错误以保持自己的理智,但其他答案已经比我先回复了。


我认为你应该在匿名函数中调用getHue()。 - RMorrisey
你说得对 - 我已经在我的代码中修复了那个问题。我当时很慌乱,做错了一些事情。另一个答案实际上是有能力的。 - Kelly Robins

1
$(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);
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接