在JavaScript中生成随机颜色的最佳方法? [英] Best way to generate a random color in javascript?
本文介绍了在JavaScript中生成随机颜色的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在不使用任何框架的情况下在JavaScript中生成随机颜色的最佳方法是什么...
What is the best way to generate a random color in JavaScript Without using any frameworks...
以下是我提出的几种解决方案:
Here are a couple of solutions I came up with:
function get_random_color()
{
var color = "";
for(var i = 0; i < 3; i++) {
var sub = Math.floor(Math.random() * 256).toString(16);
color += (sub.length == 1 ? "0" + sub : sub);
}
return "#" + color;
}
function get_rand_color()
{
var color = Math.floor(Math.random() * Math.pow(256, 3)).toString(16);
while(color.length < 6) {
color = "0" + color;
}
return "#" + color;
}
有更好的方法吗?
推荐答案
一种较短的方法:
'#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6)
这篇关于在JavaScript中生成随机颜色的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文