Appearance
html
<!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>
#code-box {
width: 100px;
height: 50px;
border: 1px solid red;
user-select: none;
line-height: 50px;
text-align: center;
}
</style>
</head>
<body>
<div class="code-box" id="code-box">AAAA</div>
<script>
/*
四位验证码规则:随机获取数字+字母(大小写)四位即可
一加载页面,就生成四位验证码,放到box中,点击box时,重新生成验证码
*/
let codeBox = document.getElementById("code-box")
// 生成验证码(可重复)
function createCode () {
// 验证码取值范围(索引范围0-61)
let area = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM',
codeText = ''
// 获取随机四位
for (let i = 0; i < 4; i++) {
codeText += area.charAt(Math.floor(Math.random() * 62))
}
codeBox.innerText = codeText
}
// 生成验证码(不重复)
function createCode () {
// 验证码取值范围(索引范围0-61)
let area = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM',
codeText = ''
// 获取随机四位,同一个字符大小写字母也算重复
// for (let i = 0; i < 4;) {
// let char = area.charAt(Math.round(Math.random() * 61))
// if (!codeText.toUpperCase().includes(char.toUpperCase())) {
// codeText += char
// i++
// }
// }
while (codeText.length < 4) {
let char = area.charAt(Math.round(Math.random() * 61))
if (!codeText.toUpperCase().includes(char.toUpperCase())) {
codeText += char
}
}
codeBox.innerText = codeText
}
// 加载页面就执行
createCode()
// 点击盒子更新验证码
codeBox.onclick = createCode
</script>
</body>
</html>