温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JS如何实现随机生成验证码

发布时间:2021-09-06 13:37:42 来源:亿速云 阅读:224 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关JS如何实现随机生成验证码的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

具体内容如下

JS如何实现随机生成验证码

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title></title>
  <style>   
  </style>
 </head>
 <body>
  <div>
  <h2>111111</h2><a href="#" rel="external nofollow" >看不清换一张</a>
  </div>
  验证码:<input type="text" value="" />
  <button>确定</button>
 </body>
 <script>
  var 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",
       "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];
        var h2=document.querySelector("h2");
        var btn=document.querySelector("button");
        var change=document.querySelector("a");     
        var input=document.querySelector("input");         
         function fn(){
        var arr1=Math.floor(Math.random()*62);
        var arr2=Math.floor(Math.random()*62);
        var arr3=Math.floor(Math.random()*62);
        var arr4=Math.floor(Math.random()*62);
        var arr5=Math.floor(Math.random()*62);
        var arr6=Math.floor(Math.random()*62);
        var yz=""+arr[arr1]+arr[arr2]+arr[arr3]+arr[arr4]+arr[arr5]+arr[arr6];
            h2.innerHTML=yz;    
            btn.onclick=function(){
              alert(input.value);
             if(input.value==yz){
            alert("正确");
            }else{
             alert("错误");
            }
           
            }
         }
        fn();
    change.addEventListener("click",fn);
 </script>
</html>

1、Math.floor() 方法

Math.floor(x)

floor() 方法返回小于等于x的最大整数。

如果传递的参数是一个整数,该值不变。

2、Math.random()方法

random() 方法可返回介于 0(包含) ~ 1(不包含) 之间的一个随机数。

使用以上两种方法可以实现取随机数的功能

感谢各位的阅读!关于“JS如何实现随机生成验证码”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI