开发者

How do I randomly generate HTML hex color codes using JavaScript? [duplicate]

This question already has a开发者_运维百科nswers here: Closed 10 years ago.

Possible Duplicate:

Random Color generator in 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?


This will generate a random number within the bounds and convert it to hexadecimal. It is then padded with zeros so that it's always a valid six-digit hex code.

'#'+(Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0');


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:

var randomColor = "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});

That replaces each of six 0s with a random hex digit, so it's sure to end up with a full six-digit valid color value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜