JS实现随机验证码登录

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .login {
        width: 236px;
        height: 90px;
        background-color: aqua;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border: 2px solid blue;
        border-radius: 7px;
        position: absolute;
        top: 50%; 
        left: 50%;
        transform: translate(-50%,-50%);
      }
      .input {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        margin-top: 10px;
      }
      .input input {
        border: 0;
        outline: none;
      }
      .input div {
        width: 36px;
        height: 19px;
        margin-left: 6px;
        padding: 0 5px;
        background-color: pink;
        border-radius: 4px;
      }
    </style>
  </head>
  <body>
    <div class="login">
      <span>验证码登录</span>
      <div class="input">
        <input id="txt" type="text" name="" placeholder="请输入验证码" />
        <div id="code">1d1s</div>
      </div>
      <div class="button">
        <button id="btn">登录</button>
      </div>
    </div>
    <script>
      var code = document.getElementById("code");
      var txt = document.getElementById("txt");
      var btn = document.getElementById("btn");

      //    生成验证码的函数
      function coderandom(codelen) {
        var str = "abcdef1234567890";
        var strcode = "";
        for (var i = 0; i < codelen; i++) {
          var n = Math.floor(Math.random() * str.length);
          strcode+=str[n]
        }
        code.innerText=strcode
      }
      coderandom(4);
      // 点击验证码  切换验证码
      code.onclick = function () {
        coderandom(4);
      };

    //   点击登录 进行判断
    btn.onclick=function(){
        if(txt.value===code.innerText){
            alert("验证码正确")
            location.href="https://blog.csdn.net/weixin_62765236?type=blog"
        }else{
            alert("验证码不正确")
        }
    }
    </script> 
  </body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_62765236/article/details/127242645