<!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>
.box {
width: 350px;
height: 500px;
background-color: #ccc;
margin: 100px auto;
}
.top {
display: flex;
}
.yzm {
text-align: center;
padding-top: 10px;
box-sizing: border-box;
/* transform: translate(-50%,-50%); */
width: 100px;
height: 50px;
color: #fff;
background-color: aqua;
margin-right: 20px;
}
</style>
</head>
<body>
<div class="box">
<div class="top">
<div class="yzm" id="yzm">1232</div>
<p id="btn">刷新</p>
</div>
<div class="bottom">
<input type="text" id="input" />
<button id="submit">确定</button>
</div>
</div>
</body>
<script>
function fn() {
let str = "";
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"];
for (let i = 0; i < 6; i++) {
let num = Math.round(Math.random() * (15 - 0) + 0); //得到下标
str += arr[num];
}
// 返回给函数
return str;
}
// 页面进行加载就获取验证码
window.onload = function () {
document.getElementById("yzm").innerText = fn();
};
document.getElementById("btn").onclick = function () {
document.getElementById("yzm").innerText = fn();
};
document.getElementById("submit").onclick = function () {
// console.log( document.getElementById("input").value);
// // 输入框的对比
document.getElementById("input").value===document.getElementById("yzm").innerText
? alert('输入正确')
: alert('输入错误') , document.getElementById("input").value = "";
};
</script>
</html>
效果图:
刷新的时候:
逻辑思路的分析:
1.通过for循环拿到随机的6位数字
2.定义a-f的数组,通过下标的形式获取数组的内容
3.通过str的形式进行拼接
4.进页面的时候加载函数赋值
5.通过对比验证码和输入框的值,写出相应的逻辑。