{
    分享网正式开通,我们为大家提供免费资源,欢迎大家踊跃投稿!

JS的几种方法实现随机颜色

JS的几种方法实现随机颜色

前言:

JS随机颜色有很多地方要用到:比如大家看到很多标签连接都是五颜六色。实现随机颜色的方法有多种,下面来看看具体的实现代码:

 

方法一:

var getRandomColor = function() {
    
    return '#' +
        (function(color) {
            return (color += '0123456789abcdef' [Math.floor(Math.random() * 16)]) && (color.length == 6) ? color : arguments.callee(color);
        })('');
}

随机生成6个字符然后再串到一起,闭包调用自身与三元运算符让程序变得内敛;其实分解开来,代码相当于:

function _g(color) {

    if ((color += '0123456789abcdef' [Math.floor(Math.random() * 16)]) && (color.length == 6)) {
        return color
    } else {
        return arguments.callee(color);
    }
}
var getRandomColor = function() {
    return '#' + _g('');
}

首先从getRandomColor函数里面传过来一个空字符串,首先连接上’0123456789abcdef’字符串里面随机的一个字母,也就是这段代码:color += ‘0123456789abcdef'[Math.floor(Math.random()*16)];

然后判断color这个变量的长度是不是为6,因为标准的颜色值是一个长度为6的字符串,第一次执行为1,所以不满足,执行问号后面的arguments.callee(color);自调用;

 

方法二:

var getRandomColor = function() {

    return (function(m, s, c) {
        return (c ? arguments.callee(m, s, c - 1) : '#') +
            s[m.floor(m.random() * 16)]
    })(Math, '0123456789abcdef', 5)
}

把Math对象,用于生成hex颜色值的字符串提取出来,并利用第三个参数来判断是否还继续调用自身。

 

方法三:

//随机颜色,十六进制方法;
function getRandomColor( ) {
    var rand = Math.floor(Math.random( ) * 0xFFFFFF).toString(16);
    if(rand.length == 6){
        return rand;
    }else{
        return getRandomColor();
    }
}

这个方法用到了十六进制与十进制的转换,我们熟知的颜色值比如#ffffff这种写法是十六进制颜色写法,将其转换为十进制之后得到16777215;转换代码如下:

var a="#ffffff"
console.log(parseInt(a.slice(1),16))   // ==> 16777215

然后我们再将16777215转换为十六进制,可以得到ffffff,前面的#号在十六进制中就是0x,所以就有了上面代码中的0xFFFFFF了;

var a=16777215
console.log(a.toString(16))   // ==> ffffff

方法四:HSL模式颜色随机;

var getRandomColor = function() {
    return "hsl(" + Math.round(Math.random() * 360) + "," + Math.round(Math.random() * 100) + '%,' + Math.round(Math.random() * 100) + '%)';
}

方法五:RGB模式随机;

var getRandomColor = function() {
    return "rgb(" + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + ',' + Math.round(Math.random() * 10) + ')';
}

方法六:RGB模式随机另外一种方法;

var getRandomColor = function () {
    var r = Math.round(Math.random() * 255), g = Math.round(Math.random() * 255), b = Math.round(Math.random() * 255);
    var color = r << 16 | g << 8 | b;
    return "#" + color.toString(16)
}

资源均来自第三方,谨慎下载,前往第三方网站下载 解压密码:www.xkwo.com 解压密码:www.xkwo.com 解压密码:www.xkwo.com 解压密码:www.xkwo.com 解压密码:www.xkwo.com 解压密码:www.xkwo.com 解压密码:www.xkwo.com 解压密码:www.xkwo.com


米微资源分享网 , 版权所有丨本站资源仅限于学习研究,严禁从事商业或者非法活动!丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:JS的几种方法实现随机颜色
喜欢 ()分享 (0)