开发者

Apply random color to class elements individually?

开发者 https://www.devze.com 2022-12-08 13:16 出处:网络
My goal is to each div with a class of \"mai开发者_如何学编程n\" to have a random background color. I have the script that generates the random color but, using jquery, I only seem to be able to apply

My goal is to each div with a class of "mai开发者_如何学编程n" to have a random background color. I have the script that generates the random color but, using jquery, I only seem to be able to apply it to all divs in the class. How can I select a div, apply the color, select the next div in the class, generate a new random color, apply it and repeat? Here's my code:

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


The code should be something like this...

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

Bah- sorry for the mistakes. Fixed the worst of them for my own sanity's sake.. but the other answer beat me to it.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号