纯JS实现验证码生成与检验
- 使用语言:HTML+CSS+JS
- 开发工具:VSCode
- 功能说明:可以实现验证码的自动产生,可以切换验证码,同时可以进行验证码的检验
- 效果展示:
- 构建思路:使用数组来进行验证码的产生,当点击后调用产生验证码的函数更新验证码,检验时通过获取验证码和用户输入的验证码进行比对,成功就弹出成功,失败就清空验证码输入框。
- 项目源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证码</title>
</head>
<style>
*{
padding: 0px;
margin: 0px;
}
.box{
height: 300px;
width: 200px;
margin: 20px auto;
}
.box>input{
margin-left: 50px;
}
#code{
background:#eee;
font-size: 25px;
margin-right: 6px;
color: blue;
cursor: pointer;
}
.show{
height: 40px;
width: auto;
}
.show button{
height: 30px;
background-color: #eee;
border: black solid 1px;
border-radius: 10px;
font-size: 10px;
}
.input{
height: 40px;
width: auto;
margin-top: 10px;
}
.input label{
float: left;
margin-right: 10px;
font-size: 20px;
}
#checkCode{
width: 80px;
height: 20px;
float: left;
}
</style>
<body>
<div class="box">
<div class="show">
<span id="code"></span>
<button id="change">看不清,换一张</button>
</div>
<div class="input">
<label for="checkCode">验证码:</label>
<input type="text" id="checkCode">
</div>
<input type="button" value="确定" id="confirm">
</div>
</body>
</html>
<script>
window.onload = function(){
var s = getCode();
function getCode(){
var array = ['1','2','3','4','5','6','7','8','9','a','b','c','e','f'];
var str = '';
for(let i = 0; i < 4; i++)
{
var index = parseInt((Math.random()*14));
str+=array[index];
}
return str;
}
document.getElementById('code').innerText = s;
document.getElementById('change').onclick = function(){
document.getElementById('code').innerText = getCode();
}
document.getElementById('confirm').onclick = function(){
var x = document.getElementById('checkCode').value;
var y = document.getElementById('code').innerText;
if(x == y)
alert("验证成功");
else
{
alert("验证码输入错误");
document.getElementById('checkCode').value = '';
}
}
}
</script>