js随机颜色获取,点击按钮换背景颜色

<style>
        .box {
            width: 200px;
            margin: 100px auto;
        }

        #box {
            width: 200px;
            height: 200px;
            background-color: aqua;
        }
    </style>

<body>
    <div class="box">
        <div id="box"></div>
        <input type="button" value='点击换色'>
    </div>
    <script>
        //点击按钮换背景颜色
        //获取标签
        var box = document.getElementById('box')
        var inp = document.querySelector('input')
        //给按钮一个点击事件
        inp.onclick = function () {
            let color = '#'
            //随机生成一个六位数
            for (let i = 0; i < 6; i++) {
                    let num = Math.round(Math.random() * 15)
                    //转化为16进制
                    num = num.toString(16);
                    color += num;
                    //console.log(color)
            }
            box.style.backgroundColor = color;
        }
    </script>
</body>

猜你喜欢

转载自blog.csdn.net/q12as/article/details/119964010