jQuery随机颜色foreach div [英] jquery random colors foreach div

查看:85
本文介绍了jQuery随机颜色foreach div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的函数遇到这个问题,我正在尝试将一些颜色(预定义)随机分配到div中,并在每次使用颜色时进行计数.

I have this issue with my function and I'm trying to randomize some colors (predefined) to my divs and count each time a color has been used.

这是我的html:

<div class="change_color2" id="rand_1"></div>
<div class="change_color2" id="rand_2"></div>
<div class="change_color2" id="rand_3"></div>
<div class="change_color2" id="rand_4"></div>
<div class="change_color2" id="rand_5"></div>

有些div将具有随机颜色作为背景:

And some divs that are going to have as background the random color:

<div class="change_color"></div>

这是我的js代码:

function colorfy_me() {
    var myColors = [
        '#543326', '#5EC631', '#A9D7DC', '#003946', '#E0D8C8'
    ];
    shuffleArray(myColors);
    var i = 1;
    $('div.change_color').each(function() {
        $(this).css('background-color', myColors[i]);
        i = (i + 1) % myColors.length;
    });
}    

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

但是问题是它会随机更改集合中前5个div的颜色. 而且我不知道如何计算每种颜色.

But the problem is that it changes the colors randomly for the first 5 divs in sets. And I don't know how to count each color.

我已经创建了一个小提琴

推荐答案

我最终得到了这个: http://jsfiddle.net/GXVUE/1/

它只是将统计信息以class ="stats"输出到div中.

It just outputs the stats into the div with class="stats".

(function($){

  var colors = ['#f00', '#0f0', '#00f']
    , colorsUsed = {}
    , $divsToColor = $('.random-color');

  $divsToColor.each(function(){

    var $div = $(this)
      , randomColor = colors[ Math.floor( Math.random() * colors.length ) ];

    $div.css('backgroundColor', randomColor);

    // Keeps track of how often a color is used...
    if( colorsUsed[randomColor] ){
        colorsUsed[randomColor]++;
    } else {
        colorsUsed[randomColor] = 1;
    }

  });

  // This reads through the stats.
  $('.stats').html(function(){
      var out = [];
      for( var color in colorsUsed ){
          out.push( color + ' was used ' + colorsUsed[color] + ' times.' );
      }
      return out.join('<br>');
  });

})(jQuery);

这篇关于jQuery随机颜色foreach div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆