JavaScript系列---【Math函数--随机生成验证码案例】

html代码:

  <span id="show"></span>

css代码:

 <style>
        span {
            display: block;
             200px;
            height: 50px;
            background-color: pink;
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            text-align: center;
            line-height: 50px;
            font-size: 30px;
            user-select: none;
        }
    </style>

js代码:

 <script>
        // 获取元素
        var show = document.getElementById("show");
        // 准备的数据
        var str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        var colors = "0123456789abcdef";
        // 页面初始化
        show.innerHTML = getChar();
        // 点击生成随机验证码(4位)
        show.onclick = function () {
            // 给span重新赋值
            show.innerHTML = getChar();
        }
        function getChar() {
            // 保存字符
            var char = "";
            var color = "#";
            // 循环
            for (var i = 0; i < 4; i++) {
                //根据随机索引值 从字符串随机的获取对应字符
                char += str.charAt(Math.round(Math.random() * (str.length - 1)));
            }
            // 设置颜色
            for (var j = 0; j < 3; j++) {
                color += colors.charAt(Math.round(Math.random() * (colors.length - 1)));
            }
            // 设置颜色
            show.style.backgroundColor = color;
            console.log(color);
            // 将拼接好的随机字符返回
            return char;
        }
    </script>

效果图:

原文地址:https://www.cnblogs.com/chenhaiyun/p/14546677.html