封装一个获取随机颜色的函数

封装一个获取随机颜色的函数

要求:该函数接收一个布尔类型参数,表示颜色的格式是十六进制还是rgb格式

  • @description:获取随机颜色
  • @param {type} flag:布尔类型 true: 十六进制颜色 false:rgb格式颜色
  • @return: 随机颜色
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 300px;
            height: 300px;
            border: 1px solid #000;
            margin: auto;
            float: left;
            margin-right: 20px;
            font-size: 36px;
            line-height: 300px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div class="one">十六进制</div>
    <div class="two">RGB</div>

    <script>
        function getRandomColor(flag) {
            if (flag) {
                let str = '';
                for (var i = 0; i < 6; i++) {
                    str += Math.floor(Math.random() * 16).toString(16);

                }
                return '#' + str.toLowerCase()
            } else {
                let r = parseInt(Math.random() * 256)
                let g = parseInt(Math.random() * 256)
                let b = parseInt(Math.random() * 256)
                return `rgb(${r},${g},${b})`
            }

        };
        let one = document.querySelector('.one');
        let two = document.querySelector('.two');
        one.style.background = getRandomColor(true);
        two.style.background = getRandomColor(false);

        console.log(getRandomColor(true)); //#fabc12
        console.log(getRandomColor(false)); //rgb(128,65,88)
    </script>
</body>

</html>
  1. toString(16); 进制转换为16进制
  2. Math.floor() 返回小于或等于一个给定数字的最大整数。
    Note: Math.floor() === 向下取整
  3. Math.random() 函数返回一个浮点, 伪随机数在范围[0,1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值