Javascript 来自数组的随机颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14949011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:25:11  来源:igfitidea点击:

Random Color From Array

javascripthtmlrandomhexbackground-color

提问by Tomelower

I'm looking to build something with JavaScript that will pick a random value (background-color) from an array of given hex colors and apply it to a given div element.

我希望用 JavaScript 构建一些东西,从给定的十六进制颜色数组中选择一个随机值(背景颜色)并将其应用于给定的 div 元素。

Anyone know a good way to do this? Nothing seems to be working for me but I'm not really a JS savvy person.

有人知道这样做的好方法吗?似乎没有什么对我有用,但我并不是一个真正精通 JS 的人。

回答by Austin Brunkhorst

How about this?

这个怎么样?

var rgb = [];

for(var i = 0; i < 3; i++)
    rgb.push(Math.floor(Math.random() * 255));

myDiv.style.backgroundColor = 'rgb('+ rgb.join(',') +')';

If you want to constrict it to known colors, you can create an array of the colors and randomly select it like so.

如果您想将其限制为已知颜色,您可以创建一个颜色数组并像这样随机选择它。

var colors = ['red', 'green', 'blue', 'orange', 'yellow'];

myDiv.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];

JSFiddle

JSFiddle

Update- Using the first method to apply to all .post-content.

更新- 使用第一种方法应用于所有.post-content.

var divs = document.querySelectorAll('.post-content');

for(var i = 0; i < divs.length; i++)
    divs[i].style.backgroundColor = 'rgb('+ rgb.join(',') +')';

If you want to apply a random background to each .post-contentindividually, you would do this.

如果您想对每个.post-content单独应用随机背景,您可以这样做。

var divs = document.querySelectorAll('.post-content');

for(var i = 0; i < divs.length; i++) {
    var rgb = [];

    for(var i = 0; i < 3; i++)
        rgb.push(Math.floor(Math.random() * 255));

    divs[i].style.backgroundColor = 'rgb('+ rgb.join(',') +')';
}

Last Update- using jQuery, as you mentioned.

上次更新- 正如您所提到的,使用 jQuery。

var colors = ['red', 'green', 'blue', 'orange', 'yellow'];

$('.post-content').each(function() {
    $(this).css('background-color', colors[Math.floor(Math.random() * colors.length)]);
});

回答by kennebec

This example returns a random item from any array, if you pass a non-falsey argument, it removes the item from the array.

此示例从任何数组中返回一个随机项,如果您传递一个非假参数,它将从数组中删除该项。

Array.prototype.getRandom= function(cut){
    var i= Math.floor(Math.random()*this.length);
    if(cut && i in this){
        return this.splice(i, 1)[0];
    }
    return this[i];
}

//sample:

//样本:

var colors= ['aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 
'lime', 'maroon', 'navy', 'olive', 'orange', 'purple', 'red', 
'silver', 'teal', 'white', 'yellow'];

alert(colors.getRandom());

警报(颜色。getRandom());

回答by kiradotee

Not sure how well this goes performance wise, but if you're already using lodash it can be as simple as:

不确定这在性能方面有多好,但如果你已经在使用 lodash,它可以很简单:

// initialising array of colours
let colours = ['tomato', 'salmon', 'plum', 'olive', 'lime', 'chocolate']

// getting a random colour
colours = _.shuffle(colours); // you can shuffle it once, or every time
let hereIsTheColour = colours.pop() // gets the last colour from the shuffled array (also removes it from the array)