JS生成随机颜色

发布时间 2023-04-07 16:21:58作者: wxxwjef
// 传统写法
    function randomColor1() {
        var r = Math.floor(Math.random() * 256),
            g = Math.floor(Math.random() * 256),
            b = Math.floor(Math.random() * 256);
        return `rgb(${r},${g},${b})`;
    }
// 取巧
    function randomColor2() {
        var color = '#' + Math.random().toString(16).substring(2,8);
        return color.length !== 7 ? randomColor2() : color;
    }