我希望用JavaScript构建一些东西,它将从给定的十六进制颜色数组中挑选一个随机值(背景色),并将其应用于给定的div元素。
有谁知道做这件事的好方法吗?似乎没有什么对我有效,但我并不是一个真正精通JS的人。
发布于 2013-02-19 10:54:03
这个怎么样?
var rgb = [];
for(var i = 0; i < 3; i++)
rgb.push(Math.floor(Math.random() * 255));
myDiv.style.backgroundColor = 'rgb('+ rgb.join(',') +')';如果您想将其限制为已知的颜色,您可以创建一个颜色数组并随机选择它,如下所示。
var colors = ['red', 'green', 'blue', 'orange', 'yellow'];
myDiv.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];更新-使用第一种方法应用于所有.post-content。
var divs = document.querySelectorAll('.post-content');
for(var i = 0; i < divs.length; i++)
divs[i].style.backgroundColor = 'rgb('+ rgb.join(',') +')';如果您想对每个.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(',') +')';
}上次更新-使用jQuery,正如您所提到的。
var colors = ['red', 'green', 'blue', 'orange', 'yellow'];
$('.post-content').each(function() {
$(this).css('background-color', colors[Math.floor(Math.random() * colors.length)]);
});发布于 2013-02-19 10:54:04
此示例从任何数组中返回一个随机项,如果您传递一个非falsey参数,它将从数组中删除该项。
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];
}//示例:
var colors= ['aqua', 'black', 'blue', 'fuchsia', 'gray', 'green',
'lime', 'maroon', 'navy', 'olive', 'orange', 'purple', 'red',
'silver', 'teal', 'white', 'yellow'];alert(colors.getRandom());
发布于 2018-04-05 18:09:08
我不确定这在性能方面有多好,但如果你已经在使用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)https://stackoverflow.com/questions/14949011
复制相似问题