详细代码如下:
<!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">
<title>Document</title>
<style>
.v_code {
width: 600px;
margin: 0 auto;
}
.v_code>input {
width: 60px;
height: 36px;
margin-top: 10px;
}
.code_show {
overflow: hidden;
}
.code_show span {
display: block;
float: left;
margin-bottom: 10px;
}
.code_show a {
display: block;
float: left;
margin-top: 10px;
margin-left: 10px;
}
.code {
font-style: italic;
background-color: #f5f5f5;
color: blue;
font-size: 30px;
letter-spacing: 3px;
font-weight: bolder;
float: left;
cursor: pointer;
padding: 0 5px;
text-align: center;
}
#inputCode {
width: 100px;
height: 30px;
}
a {
text-decoration: none;
font-size: 12px;
color: #288bc4;
cursor: pointer;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="v_code">
<div class="code_show">
<span class="code" id="checkCode"></span>
<a id="linkbt">看不清换一张</a>
</div>
<div class="input_code">
<label for="inputCode">验证码:</label>
<input type="text" id="inputCode" />
<span id="text_show"></span>
</div>
<input id="Button1" type="button" value="确定" />
</div>
<script>
//6位数 0-9 a-f 随机生成,内容必须是0-9 a-f字符串
window.onload = function () {
var res = getCode();//当页面加载的时候调用下面获取6位字符串的方法
document.getElementById('checkCode').innerText = res;//把它赋值给span显示
//获取6位字符串的方法
function getCode() {
//定义字符数组
var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
var str = '';//定义空的字符串,作为最终的结果接收它
for (var i = 0; i < 6; i++) {
var num = Math.round(Math.random() * (15 - 0) + 0);//0-15的随机数
str += arr[num];//通过产生的随机数来获取数组中的内容
}
return str;
}
//当点击连接换一张时调用方法重新生成6位字符串赋值给span
document.getElementById('linkbt').onclick = function () {
document.getElementById('checkCode').innerText = getCode();
}
//功能2:提交时进行验证输入是否正确
document.getElementById('Button1').onclick = function () {
var code = document.getElementById('checkCode').innerText;
var inputCode = document.getElementById('inputCode').value;
if (code != inputCode) {
alert('您输入的验证码不正确');
//让输入框为空,清空输入框
document.getElementById('inputCode').value = '';
}
}
}
</script>
</body>
</html>
结果:初始页面,每当页面刷新一次,自动更新验证码:
当点击看不清更换一张时,更换验证码:
当输入验证码错误,点击确定时,进行提示:
点击确定后自动清空验证码: