随机验证码

在登录或者注册页面输入表单时,会让你输入验证码进行账号绑定,一般验证码都是后台在弄,前端一般都是获取验证码传递给后端。
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        #app{
            width: 80%;
            margin:40px auto;
        }
        #code{
            width: 200px;
            height: 200px;
            border: 1px solid rgba(114, 114, 114, 0.27);
            text-align: center;
            line-height: 200px;
            color: orangered;
            font-size: 36px;
            font-style: italic;
        }
         .yz{
             margin: 10px;
         }
    </style>
</head>
<body>
<div id="app">
    <div id="code"></div>
    <div class="yz">
        <input type="text" id="text">
        <button type="button" id="vaildata">验证</button>
    </div>
</div>
<script>
window.onload=function () {
    let div=document.getElementById("code")
    let text=document.getElementById("text")
    let btn=document.getElementById("vaildata")
    let code=""
    let codelength=4
    let randCode=[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g',
        'H','I','J','K','L','M','N']

 

    for(let i=0;i<codelength;i++){
        //设置随机范围
        let index=Math.floor(Math.random()*randCode.length)
       // console.log(index);
       // console.log(randCode[index]);
        code+=randCode[index]
    }
    div.innerText=code

 

    btn.onclick=function () {
      // console.log(text.value);
        if(text.value==code){
               alert("验证成功")
               text.value=""
        }else if(text.value.length==0){
            alert("请输入验证码")
        }else {
            alert("验证失败")
            text.value=""
        }
    }

 

}
</script>
</body>
</html>
posted @ 2020-06-17 23:31  岱宗如何  阅读(250)  评论(0编辑  收藏  举报