2020-09-04

JS实现随机生成16进制颜色

<!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 type=text/css>
        a {
     
            display: block;
            width: 200px;
            height: 50px;
            background: purple;
            color: white;
            text-align: center;
            line-height: 50px;
            text-decoration: none;
            display: block;
            margin: 0 auto;
        }
        .tt {
     
            width: 200px;
            height: 100px;
            margin: 50px auto;
            display: block;
            text-align: center;
            line-height: 100px;
        }
    </style>
</head>
<body id="aa">
    <a href="javascript:;" id="btn">点击切换下面盒子背景色</a>
    <h3 class="tt" id="txt">这里可以变色哦</h3>
    
    <script>
    
    function random(m, n) {
     
            var num = m + parseInt(Math.random() * (n - m));
            return num;
        }
    function randomColor() {
     
            var result = "#";
            for (var i = 0; i < 6; i++) {
     
            result = result + random(0, 15).toString(16);//调用随机数函数并转为16进制,16进制为0到15,就像十进制为0到9一样,所以random里面为0到15
            }
            return result;
        }
        
        //下面就是简单的点击事件了
        var anniu = document.getElementById("btn");
		anniu.onclick = function () {
     
	    var wenBen = document.getElementById("txt");
        console.log(wenBen)
        wenBen.style.background = randomColor();
        }
          </script>
          
</body>
</html>

效果图如下
2020-09-04_第1张图片
2020-09-04_第2张图片

你可能感兴趣的:(javascript)