六位数字字母验证码
效果图
html部分
<body> <input type="text" id="ipt"/> <div id="box" onclick="reset()"></div> </body>
input部分是需要输入的部分,div部分是自动生成的验证码
style部分
<style> #box{ width:180px; height: 50px; text-align: center; border:1px solid #ccc; cursor: pointer; background:linear-gradient(to top,#0072e5,#3f9efe) } #box span{ display: inline-block; font-size: 26px; width:16px; height: 50px; line-height: 50px; font-family: "microsoft yahei"; -webkit-text-stroke: 1px #ccc; } </style>
js部分
<script> //验证码 6位数的验证码 function authCode(){ var str = ''; while(str.length<6){ var num = random1Num(48,122) if((num>57&&num<65)||(num>90&&num<97)){ num = random1Num(48,122) }else{ str += '' + String.fromCharCode(num) } } return str } //随机数 n小于m function random1Num(n,m){ return parseInt(n+Math.random()*(m-n+1)); } //随机颜色 function randomColor(){ var R = random1Num(0,255) var G = random1Num(0,255) var B = random1Num(0,255) return "#"+string2Num(R,G,B) } //转换为16进制不足补0 function string2Num(r,g,b){ r = r.toString(16).length<2?"0"+r.toString(16):r.toString(16); g = g.toString(16).length<2?"0"+g.toString(16):g.toString(16); b = b.toString(16).length<2?"0"+b.toString(16):b.toString(16); return r+g+b; } var code = authCode() // $("#box").text(code) //将字符串转成数组 var arrcode = code.split('') //将数组放进单个的span标签中 for(var i = 0;i < arrcode.length;i++){ $("#box").append('<span>'+arrcode[i]+'</span>') $("span:nth-child("+ (i+1) +")").css({ "color":randomColor(), "transform":"rotate("+random1Num(-30,30) +"deg)", "fontSize":""+ random1Num(24,36) +"px", "marginTop":""+ random1Num(-3,3) +"px", "marginLeft":""+ random1Num(-2,6) +"px", "marginRight":""+ random1Num(-2,8) +"px" }) } //点击生成新的验证码 function reset(){ //清除原有的数据 $("#box span").remove() $("#ipt").val("") //重新生成验证码 code = authCode() arrcode = code.split('') for(var i = 0;i<arrcode.length;i++){ $("#box").append('<span>'+arrcode[i]+'</span>') $("span:nth-child("+ (i+1) +")").css({ "color":randomColor(), "transform":"rotate("+random1Num(-30,30) +"deg)", "fontSize":""+ random1Num(24,36) +"px", "marginTop":""+ random1Num(-3,3) +"px", "marginLeft":""+ random1Num(-2,6) +"px", "marginRight":""+ random1Num(-2,8) +"px", }) } } //校验 $("#ipt").on("blur",function(){ //都转成小写,即不区分大小写 if($("#ipt").val() != ""){ if($("#ipt").val().toLowerCase() == code.toLowerCase()){ alert("验证码输入正确!") }else{ alert("验证码输入错误!") } } }) </script>