跳到主要内容

随机色值

一、RGB 随机色值


实现

function randomColorRGB() {
let r = (Math.random() * 256) >> 0;
let g = (Math.random() * 256) >> 0;
let b = (Math.random() * 256) >> 0;
return `rgb(${r},${g},${b})`;
}

console.log(randomColorRGB());

二、十六进制色值


实现

function randomColor16() {
let r = ((Math.random() * 256) >> 0).toString(16);
let g = ((Math.random() * 256) >> 0).toString(16);
let b = ((Math.random() * 256) >> 0).toString(16);
if (r.length < 2) {
r = "0" + r;
}
if (g.length < 2) {
g = "0" + g;
}
if (b.length < 2) {
b = "0" + b;
}
return `#${r}${g}${b}`;
}