【问题标题】:Apply random color to class elements individually?将随机颜色单独应用于类元素?
【发布时间】:2010-12-04 20:12:41
【问题描述】:

我的目标是让每个具有“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);
});

【问题讨论】:

    标签: javascript jquery css


    【解决方案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);
        });
    });
    

    【讨论】:

    • 完美,但我有疑问。有什么方法可以只显示深色。它一直显示浅色。请帮忙
    【解决方案2】:

    代码应该是这样的......

    $(document).ready(function() {
                            $('.main').each{ Function(){
                                 $(this).css("background-color", hue); };
                            };
                    });
    

    呸——对错误感到抱歉。为了我自己的理智,修复了其中最糟糕的一个。但另一个答案打败了我。

    【讨论】:

    • 我认为你应该在匿名函数中调用 getHue()
    • 你说得对——我刚刚在我的代码中修复了这个问题。我争先恐后,做错事。另一个答案实际上是有能力的。
    【解决方案3】:
    $(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);
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2012-07-28
      • 2013-02-22
      • 2011-12-02
      • 2015-05-25
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多