效果如下:
![请添加图片描述](https://i-blog.csdnimg.cn/blog_migrate/b182f1be0655eff997f255f14acdd4f5.gif)
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.v_code {
margin: auto;
padding: 10px;
}
.code {
background-color: #ccc;
color: blue;
}
</style>
<title>Document</title>
</head>
<body>
<div class="v_code">
<div class="code_show">
<span class="code" id="checkCode">adf34y</span>
<a href="javascript:;" id="linkbt">看不清换一张</a>
</div>
<div class="input_code">
<label for="inputCode">验证码:</label>
<input type="text" id="inputCode">
<span id="text_show"></span>
</div>
<input type="button" id="button1" value="确定">
</div>
<script>
var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
var checkCode = document.getElementById('checkCode');
var linkbt = document.getElementById('linkbt');
var str = '';
var str1 = '';
linkbt.addEventListener('click', function () {
for (var i = 0; i < 6; i++) {
str += arr[parseInt(Math.random() * 15)];
}
checkCode.innerHTML = str;
str1 = str;
str = '';
})
var inputCode = document.getElementById('inputCode');
var btn = document.getElementById('button1');
btn.addEventListener('click', function () {
if (inputCode.value === str1) {
alert('您已通过验证!');
} else {
alert('验证码输入错误!')
}
})
</script>
</body>
</html>