随机验证码:
let codeArr = [ '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',0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
这里的字符可以任意加入
<script>
let code;
function createCode() {
let codeInput = document.getElementsByClassName("code")[0];
let codeArr = [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'];
let length = 4;
code = "";
for (let i = 0; i < length; i++) {
let randomI = Math.floor(Math.random() * 62);
code += codeArr[randomI];
}
console.log(code);
if (code) {
codeInput.value = code;
}
}
function verifyCode() {
let input = document.getElementById("verify-code");
let value = input.value;
if (value.length <= 0) {
alert("输入不能为空");
input.focus();
} else if (value != code) {
alert("不匹配");
//重新给一个
createCode();
input.value = "";
input.focus();
} else {
alert("验证成功")
}
}
window.onload = function () {
createCode();
}
</script>
解析:
1、创建数组,里面包含字母和数字
2.验证码 是自定义位,这里产生4位,每次都将随机产生一个codeArr下标,相当于随机产生一个字符codeArr[下标],然后拼接起来,就是4位随机验证码 。