如何使用 JavaScript 随机生成 HTML 十六进制颜色代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5092808/
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
How do I randomly generate HTML hex color codes using JavaScript?
提问by Achilles
Possible Duplicate:
Random Color generator in Javascript
可能的重复:
Javascript 中的随机颜色生成器
I have some data I'd like to display in different colors and I want to generate the colors randomly if possible. How can I generate the Hex Color Code using JavaScript?
我有一些数据想以不同的颜色显示,如果可能的话,我想随机生成颜色。如何使用 JavaScript 生成十六进制颜色代码?
回答by DanS
'#'+(Math.random()*0xFFFFFF<<0).toString(16);
回答by Bill the Lizard
There are a variety of methods in the blog post Random hex color code generator in JavaScript. You need to pad with zeros when the random value is less than 0×100000
, so here's the correct version:
博客文章JavaScript 中的随机十六进制颜色代码生成器中提供了多种方法。当随机值小于 时,您需要用零填充0×100000
,因此这是正确的版本:
var randomColor = "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});
That replaces each of six 0
s with a random hex digit, so it's sure to end up with a full six-digit valid color value.
这用0
随机的十六进制数字替换了 6 个s 中的每一个,因此最终肯定会得到一个完整的 6 位有效颜色值。