效果图:
html内容:
<body>
<div class="v_code">
<div class="code_show">
<span class="code" id="checkCode"></span>
<a href="" id="bt">看不清换一张</a>
</div>
<div class="input_code">
<label for="inputCode">验证码:</label>
<input type="text" id="inputCode"><span id="text_show"></span>
</div>
<input type="button" value="确定" id="Button1">
</div>
</body>
style内容:
<style>
* {
margin: 0;
padding: 0;
}
.v_code {
margin: 0 auto;
width: 500px;
}
.code_show {
margin: 10px;
}
.code {
width: 200px;
line-height: 30px;
background-color: #eee;
color: blue;
font-weight: bold;
font-style: italic;
font-size: 20px;
padding: 1px 8px;
}
#bt {
text-decoration: none;
color: lightseagreen;
font-size: 13px;
}
#inputCode {
width: 80px;
height: 25px;
border: 1px solid #ccc;
}
#Button1 {
width: 50px;
line-height: 25px;
padding: 5px 0;
margin: 10px 0;
border: 1px solid #ccc;
}
#text_show {
color: red;
}
</style>
js模块:
window.onload = function () {
var text_show = document.getElementById('text_show');
var res = getCode();
// console.log(res);
// 1、 封装一个函数
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);
str += arr[num];
}
return str;
}
var checkCode = document.getElementById('checkCode');
checkCode.innerHTML = res;
var btn = document.getElementById('bt');
// 2 、 执行点击事件
btn.onclick = function () {
checkCode.innerText = getCode();
}
// 3、 提交验证码进行对比
var button = document.getElementById('Button1');
button.onclick = function () {
var code = checkCode.innerText;
var inputCode = document.getElementById('inputCode').value;
if (code != inputCode) {
// alert('您的输入有误,请重新输入!');
text_show.innerHTML = '输入有误,重新输入';
document.getElementById('inputCode').value = '';
return false;
} else {
text_show.innerHTML = '';
alert('恭喜您验证通过!');
return true;
}
}
}
</script>