html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{
width: 300px;
height: 150px;
border: 1px solid;
margin: 30px auto;
position: relative;
}
.code{
width: 120px;
height: 40px;
background-color: #D6E3BC;
border: 2px solid;
text-align: center;
font-size: 24px;
line-height: 40px;
position: absolute;
top: 20px;
left: 20px;
letter-spacing:3px;
}
a{
position: absolute;
left: 160px;
top: 30px;
color: green;
}
input{
width: 180px;
height: 20px;
top: 90px;
left: 20px;
position: absolute;
}
button{
width: 50px;
height: 26px;
position: absolute;
top: 90px;
right:26px ;
background-color: green;
color: #fff;
border: 1px solid gray;
}
</style>
</head>
<body>
<div class="box">
<div class="code" id="checkCode"></div>
<a href="#" id="btn" >看不清,换一张</a>
<input type="text" placeholder="请输入验证码" id="Input">
<button id="subBtn">验证</button>
</div>
<script>
/*实现点击“看不清,换一张”随机生成六位验证码(可包含数字和大小写字母)*/
this.code;
var Input=document.querySelector("#Input");
var btn=document.querySelector("#btn");
var subBtn=document.querySelector("#subBtn");
window.onload=function () {
yzm.createCode();
}
init();
function init() {
subBtn.onclick=function () {
yzm.isLegal()
}
btn.onclick=function () {
yzm.createCode();
}
}
var yzm={
createCode:function () {
this.code = "";//存放验证码
var codeLength = 6;//设置验证码长度为6
var checkCode = document.querySelector("#checkCode");
var codeChars = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
'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');//验证码要随机挑选的字符
for (var i = 0; i < codeLength; i++) {
var charIndex = Math.floor(Math.random() * 52);//随机产生0-52之间的整数
this.code += codeChars[charIndex];//将随机指向我们规定的字符添加到code容器里
}
if (checkCode) {
checkCode.className = "code";
checkCode.innerHTML = this.code;
}
},
isLegal:function () {
var InputValue=Input.value;
/*console.log(InputValue);
console.log(this.code);*/
if(InputValue==this.code){
alert("验证码正确!");
}else {
alert("验证码不正确,请重试!");
}
}
}
</script>
</body>
</html>