前端使用JS原生_10行实现不重复验证码

前端开发入门效果分享 青岛web前端开发项目 web前端开发初级入门

不重复的6位随机验证码非常常用,这里是最简单的两种实现方式:

(1)自动生成,(2)点击更新。
1、自动生成:每隔1秒自动生成1次。
html 代码

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <title>Title</title>
    <style>
        #yard {
            font-size: 170px;
            background: grey;
        }
    </style>
</head>
<body>
    <div id=”yard”></div>
    <script>
        var div = document.getElementById(“yard”);
        function fn() {
            var strCode = ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789’;
            var str = ”;
            while (str.length < 6) {
                var str1 = strCode.charAt(Math.round(Math.random() * 61));
                if (str.indexOf(str1) === -1) {
                    str += str1;
                }
            }
            div.innerHTML = str;
        }
        fn();
        var timer = setInterval(fn, 1000)
    </script>
</body>
</html>

2、点击更新
html 代码

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <title>Title</title>
    <style>
        #yard {
            font-size: 170px;
            background: grey;
            cursor: pointer;
            /*比“1、自动生成”多出的代码*/
            -webkit-user-select: none;
            /*比“1、自动生成”多出的代码*/
        }
    </style>
</head>
<body>
    <div id=”yard”></div>
    <script>
        var div = document.getElementById(“yard”);
        div.onclick = fn;
        function fn() {
            var strCode = ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789’;
            var str = ”;
            while (str.length < 6) {
                var str1 = strCode.charAt(Math.round(Math.random() * 61));
                if (str.indexOf(str1) === -1) {
                    str += str1;
                }
            }
            div.innerHTML = str;
        }
        fn();
    </script>
</body>
</html>

前端项目开发周期 0基础入门web前端开发 web前端开发项目经理

» 本文来自:前端开发者 » 《前端使用JS原生_10行实现不重复验证码》
» 本文链接地址:https://www.rokub.com/5734.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!