简单的验证码

使用随机数做一个简单的验证码

  1. Math.random(): 获取0~1随机数
  2. Math.random()*num: 代表 取一个> = 0 且 小于 num 的数
  3. 一般会在前面 加上一个 Math.floor() 这个代表的是取整数

下面为这个验证码的代码

style样式

    <style>
        .p1{
        width: 150px;
        height: 80px;
        line-height: 80px;
        text-align: center;
        font-size: 33px;
        font-family:Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
        
    }
    .sp1:hover{
        cursor: pointer;
        user-select: none;/* 禁止复制 */
        
        
    }
    .p2{
        color: red;
        display: none;
    }
    
    </style>

html部分

 <i><p class="p1"></p></i> 
    <form action="">
        <!-- placeholder 占位符 提示用户输入的信息内容 不影响正常输入 disabled 禁止输入 -->
        <!-- autocomplete 对用户输入的东西进行记忆 下次输入进行弹出 off关闭 on开启此功能 -->
        <input type="text" id="user" placeholder="请输入你的账号" autocomplete="on" maxlength="6">
        <!-- lable起提示作用 label中的for的值和input中id的值一样,这样就形成一种关联,选中label就选中input -->
        <label class="sp1" for="user">确认</label>
    </form>
    <p class="p2">请勿输入非数字字母以及下划线的东西</p>

Javascript部分

<script>
        var p1 = document.getElementsByTagName('p')[0];
        var sp1 = document.getElementsByClassName('sp1')[0];
        var sp2 = document.getElementsByClassName('p2')[0];
        var str = '1234567890ABCDEFGHIJKLMNOPGRSTUVWXYZ_';
        var i = 1;

        function chux() {
            var yzm = '';
            for (var i = 0; i < 6; i++) {
                yzm += str.charAt(Math.floor(Math.random() * 2));
            }
            console.log(yzm);
            p1.innerHTML = yzm;
        };
        chux();
        p1.onclick = chux;


        //正则判断一下 有没有非数字和下划线以外的东西  可要可不要
        user.oninput = function () {
            if (/[^\w]+/.test(user.value) == true) {
                sp2.style.display = 'block'
            } else {
                sp2.style.display = 'none'
            }
        }  

        sp1.onclick = function () {
            console.log(user.value);
            console.log(p1.innerHTML);
            if ((user.value).toUpperCase() == p1.innerHTML) {
                window.location.href="https://baike.baidu.com/item/%E5%8E%89%E5%AE%B3/32409?fr=aladdin";
            }else if(user.value ===''){
                alert('请输入东西鸭');
            } else {
                if (i >= 3) {
                    chux();
                    alert('输入错误已达到三次 验证码已经重新生成');
                    user.value = '';
                    i = 0
                } else {
                    alert('输入错误');
                    i++;
                }
            }

        }

ps:这个其实除了随机数和if语句以外 其它的都是累赘 大家看看就好

猜你喜欢

转载自blog.csdn.net/qq_43504375/article/details/88761099