简体   繁体   中英

Addressing background color of divs JavaScript

I am trying to target multiple div s and randomly change the background color, (or other attributes), all at once. I've been able to target the body background with document.body.style.background but I'm not sure this would work with multiple elements. Any insight would be nice.

Here is a bit of code that I'm trying to accomplish that with:

 function randBGcolor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
        for (var i=0; i<6; i++ ) {
            color += letters[Math.round(Math.random() * 15)];
        }
   document.body.style.background = color;
}

I would like to still use the random color function, but have it apply it to many elements on one click.

using jQuery and your function:

function randBGcolor() {
   var letters = '0123456789ABCDEF';
   var color = '#';
      for (var i=0; i<6; i++ ) {
         color += letters[Math.round(Math.random() * 15)];
      }
   return color;
}

$('#button').on('click', function() {
    $('div.classname').css('background-color', randBGcolor());
})

I think you can accomplish this with JQuery, you may be able to find someone who knows how in pure JS.

You can loop through multiple elements, say div tags by using each()

http://jsfiddle.net/Kwb49/ - this example changes all divs when clicking the body

$(document).ready(function() {

    $('body').click(function() {
       $('div').each(function() {
            var bgcolor = randBGcolor();
            $(this).css({ "background" : bgcolor });
        }); 
    });

});

function randBGcolor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i=0; i<6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

Pure JS solution:

http://jsfiddle.net/Kwb49/3/ (updated fiddle, works on click, added one test button)

function randBGcolor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
        for (var i=0; i<6; i++ ) {
            color += letters[Math.round(Math.random() * 15)];
        }

    return color;

}



 divs=document.getElementsByTagName('div');

    for(i=0;i<divs.length;i++) {
    divs[i].style.backgroundColor=randBGcolor();
    }

The css method can be used with a callback function, so that you can select all the elements that you want to change, and get a separate background color for each one with a single call:

function randBGcolor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * letters.length)];
  }
  return color;
}

$('.someelements').css('background-color', randBGcolor);

Demo: http://jsfiddle.net/Guffa/Tp856/

To use it in a click event, you just use the click method inside the ready event. Example:

$(document).ready(function(){
  $('.someelement').click(function(){
    $('.someelements').css('background-color', randBGcolor);
  });
});

Note: You should not use Math.random when you are calculating the random number. That will make the lowest and highest values be selected half as often as the others. Use Math.floor and mulitply with a number that is one higher.

One approach I'd suggest, in compliant browsers, using plain JavaScript is:

function randColor(n) {
    var result = [];
    for (var i = 0; i < n; i++) {
        result.push(Math.floor(Math.random() * 255));
    }
    return result.join(',');
}

function randBGColor () {
    return 'rgb(' + randColor(3) + ')';
}

var els = document.querySelectorAll('div');

[].forEach.call(els, function(a) {
    a.style.backgroundColor = randBGColor();
});

JS Fiddle demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM