本文操作环境:windows7系统、javascript1.8.5版,dell g3电脑
javascript怎么实现四位随机验证码?
js实现4位随机验证码
通过随机数编写一个不分大小写且含数字的4位随机数。
css样式
p{ width: 60px; height: 20px; display: inline-block; letter-spacing: 3px; border: 1px solid red;}#p{ height: 20px; margin-bottom: 10px;}#btn,p:hover{ cursor: default;}button{ display: block;}
主体部分
<p id="box">验证码 <input type="text" id="int" /> <p id="p"></p> <p id="p"></p> <button id="btn">提交</button></p>
js部分
//随机数function random(max,min){ return math.round(math.random()*(max-min)+min);}//随机4位验证码function code(){ //将数字、小写字母及大写字母输入 var str="1234567890qwertyuioplkjhgfdsazxcvbnmqwertyuioplkjhgfdsazxcvbnm"; //给一个空字符串 var res=''; //循环4次,得到4个字符 for(var i=0;i<4;i++){ //将得到的结果给字符串,调用随机函数,0最小数,62表示数字加字母的总数 res+=str[random(0,62)]; } p.innerhtml=res;}code(); //调用验证码函数p.onclick=code; //点击也可以刷新验证码//验证验证码btn.onclick=function(){ var int=document.getelementbyid("int").value;//获取用户输入的值 var p=document.getelementbyid("p").innertext;//获取验证码 //判断用户输入与验证码的大写一致(不分大小写) if(int.touppercase()==p.touppercase()){ p.innerhtml="验证码正确"; }else{ p.innerhtml="验证码错误"; }}
实现结果
总结
math.round():四舍五入
math.random():随机数
touppercase():将字符串转为大写
推荐学习:《javascript高级教程》
以上就是javascript怎么实现四位随机验证码的详细内容。