简体   繁体   中英

Random colours from array applied to elements on page

I have a list of elements, which all need a random background color applied to them from an array of colors.

My HTML structure is simple:

<ul class="moreorless-list">
  <li><span>Word</span></li>
  <li><span>Word</span></li>
  <li><span>Word</span></li>
  <li><span>Word</span></li>
  <li><span>Word</span></li>
  <li><span>Word</span></li>
</ul>

For example, an array of colors could be: #ffffff, #111111, #222222, #333333 etc.

I need to take the colors from the array and randomly apply them to the list; this of course would mean that some colors are repeated twice is fine.

Any ideas how I could achieve this? PHP or JS is preferred.

$('li').each(function () {
    $(this).css('background-color', random());
});

function random() {
    colors = ['red', 'white', 'blue', 'green']
    return colors[Math.floor(Math.random() * colors.length)];
}

try this:

function get_random_color() {
    function c() {
        return rand_num(256).toString(16);
      }
      return "#"+c()+c()+c();
      }

If you have a color set use this:

$colors = array("#FFFFFF", "#000000", "#333333");
$rand_keys = array_rand($colors);

Try this:

function getRandomColor(colorArray)
{
   return colorArray[Math.floor(Math.random()*colorArray.length)];
}

I'd tend to suggest:

var options = ['#ffffff', '#111111', '#222222', '#333333'];

function randomColour(el, colours){
    return colours[Math.floor(Math.random()*colours.length)];
}

var spans = document.getElementsByTagName('span');
for (var i = 0, len = spans.length; i<len; i++){
    spans[i].style.backgroundColor = randomColour(this,options);
}

JS Fiddle demo .

Basically you need to get a random value out of an array. In PHP, you can achieve this with using array_rand ( http://php.net/manual/en/function.array-rand.php ). One aproach could look something like this:

<?php
    function randomColor() {
        $colorArray = array('#ffffff', '#111111', '#222222', '#333333', ...);
        return $colorArray[array_rand($colorArray)]; // array_rand() only returns the key
    }
?>

<ul class="moreorless-list">
    <li style="background-color:<?php echo randomColor(); ?>"><span>Word</span></li>
    <li style="background-color:<?php echo randomColor(); ?>"><span>Word</span></li>
    <li style="background-color:<?php echo randomColor(); ?>"><span>Word</span></li>
    <li style="background-color:<?php echo randomColor(); ?>"><span>Word</span></li>
    <!-- ... -->
</ul>

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