原生js生成随机验证码

本文详细介绍了一种使用JavaScript在网页上生成随机验证码并进行验证的方法。通过HTML和CSS布局,结合JavaScript动态生成随机字符串作为验证码,实现了验证码的刷新和验证功能。用户可在输入框中输入验证码,点击按钮进行验证,若正确则跳转至百度页面。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js实现随机验证码功能</title>
    <style>
        *{margin:0;padding:0}
        #myform{
            width:500px;
            height:200px;
            position:absolute;
            left:0;
            right:0;
            top:0;
            bottom:0;
            margin:auto;
            border:1px solid #000;
            line-height:200px;
        }
        #box{
            width:294px;
            height:200px;
            position: absolute;
            left: 0;
            right:0;
            bottom:0;
            top:0;
            margin: auto;
        }
        input{
            height: 24px;
        }
        #code{
            width:80px;
            height:26px;
            background: #d2d2d2;
            border:  0;
        }

    </style>
</head>
<body onload="createCode()">
<form id="myform">
    <div id="box">
        <input type="text" placeholder="请输入验证码" id="myInput"/>
        <input id="code" type="button">
        <input type="button" value="验证" id="mybtn">
    </div>
</form>
</body>
<script>
    let oCode = document.getElementById('code');
    let oBtn = document.getElementById('mybtn');
    let oInput = document.getElementById('myInput');
    let str = '';
    function createCode(){
        let arr = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',0,1,2,3,4,5,6,7,8,9];
        for(let i = 0; i < 4; i++){
            //生成0-35的随机数
            str = str.concat(arr[Number.parseInt(Math.random() * 36)]);
        }
        oCode.value= str;
    }
    function check(){
        let data = oInput.value.toUpperCase().trim();
        if(data === str){
            window.location = 'https://www.baidu.com';
        }else if(data === ''){
            alert('请输入验证码');
        }else{
            alert("验证码错误");
            //记得清空输入框内容,方便用户使用
            oInput.value = '';
            //验证码也要重新生成
            str='';
            createCode();
        }
    }
    oCode.addEventListener('click',function(){
        createCode();
    });
    oBtn.addEventListener('click',function(){
        check();
    })




</script>
</html>复制代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值