随机生成验证码

思路:
1.获取div的box盒子,生成验证码后追加到盒子,span.innertext放入字符
2.获取input框内的验证码内容
3.点击btn按钮触发事件,验证输入的验证码与给出的是否一致,设置notice提醒
4.验证码不一致,则重新生成新的验证码,重新输入(将value值设为0),保留点击过的焦点
如何随机生成验证码?
1.数组放入所有数字字母字符
2.把函数获取的长度限制为4
3.循环长度,随机数*数组长度 向下取整,获取数组所有数里的随机数下标
4.设置空字符,用于连接,利用codelist[下标]即可获取任意数组里的字符
5.生成随机颜色 rgb
<!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: 120px;
height: 40px;
height: 40px;
display: flex;
justify-content: space-around;
align-items: center;
border: 3px solid blue;
cursor: pointer;
margin-bottom: 5px;
}
#box span {
font-size: 1.8em;
font-weight: bold;
}
#code {
height: 25px;
}
</style>
</head>
<body>
<div id="box"></div>
<input type="text" id="code" placeholder="请输入验证码" required />
<button id="btn">验证</button><br />
<span id="notice" style="display: none;color:red;font-size:1.5em">输入错误</span>
</body>
</html>
<script>
var box = document.getElementById('box')
var code = document.getElementById('code')
var btn = document.getElementById('btn')
var notice = document.getElementById('notice')
var CodeStr = ''
function GetCode(len = 4) {
CodeStr = ''
var str = ''
box.innerHTML = ''
var codelist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
]
for (var i = 0; i < len; i++) {
var key = Math.floor(Math.random() * codelist.length)
CodeStr += codelist[key]
var r = Math.floor(Math.random() * 255)
var g = Math.floor(Math.random() * 255)
var b = Math.floor(Math.random() * 255)
var span = document.createElement('span')
span.style.color = `rgb(${r},${g},${b})`
span.innerText = codelist[key]
box.appendChild(span)
}
}
GetCode()
btn.onclick = function () {
var input = code.value.trim()
if (input.toLowerCase() != CodeStr.toLowerCase()) {
notice.style.display = 'block'
notice.style.color = 'red'
notice.innerText = '验证码错误'
GetCode()
code.value = ''
code.focus()
} else {
notice.style.display = 'block'
notice.style.color = 'green'
notice.innerText = '验证码正确'
}
}
</script>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
- 92.
- 93.
- 94.
- 95.
- 96.
- 97.
- 98.
- 99.
- 100.
- 101.
- 102.
- 103.
- 104.
- 105.
- 106.
- 107.
- 108.
- 109.
- 110.
- 111.