<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.yanzhengma{
width: 650px;
/* background-color: #0000FF; */
height: 300px;
margin: 0 auto;
/* text-align: center; */
padding-top:20px;
}
.code{
height: 60px;
/* background-color: aqua; */
}
.code a{
width: 120px;
height: 60px;
/* background-color: aquamarine; */
display: inline-block;
position: absolute;
line-height: 70px;
margin-left: 10px;
}
#two{
display: inline-block;
position: relative;
width: 80px;
height: 30px;
margin-left: 180px;
margin-top: 20px;
/* */
background-color: #0000FF;
}
.one{
position: absolute;
line-height: 30px;
margin-left:13px;
/* padding: 4px 3px;
margin-right: 3px;
margin-bottom: 13px;
margin-left: 180px; */
}
.input{
width: 450px;
height: 50px;
/* background-color: aquamarine; */
margin-top: 10px;
margin-left: 170px;
}
#button1{
margin-left:250px;
}
</style>
</head>
<body>
<div class="yanzhengma">
<div class="code">
<div id="two">
<span class="one" id="checkcode">adfh34</span>
</div>
<a id="linkad" href="#">看不清,换一张</a>
</div>
<div class="input">
<label for="inputcode" class="">验证码</label>
<input type="text" id="inputcode" />
<span id="text_code"></span>
</div>
<input id="button1" type="button" value="确定" />
</div>
</body>
<script>
// 获取对象
var linkad = document.getElementById('linkad')
var checkcode = document.getElementById('checkcode')
// 页面打开就获取验证码
window.onload = function(){
var res = yanzhengma();
// 获取六个随机数,并封装在yanzhengma函数中。
function yanzhengma(){
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++){
// math.round方法取整,math.random方法获取一个随机小数。
let num = Math.round(Math.random()*(15 - 0) + 0);
// 注意这里str规定是空字符,不是数组,不是number值。所以可以获得六个字符的字符串。
str += arr[num];
}
return str;
}
// 把获取到的字符串传给验证码字符。
checkcode.innerText = res;
// 点击换一张字符。
linkad.onclick = function(){
let res = yanzhengma()
checkcode.innerHTML = res;
}
// 点击确定事件。
document.getElementById('button1').onclick = function(){
// 先获取验证码
var code = checkcode.innerHTML;
// 再获取输入的值。
var code1 =document.getElementById('inputcode').value;
// 两者校验。
if( code != code1){
document.getElementById('text_code').innerHTML = '验证码错误,请重新输入!'
return
}
else{
location.href = 'www.baidu.com';
}
}
}
</script>
</html>
B站学习,你我共同进步!