- 需求分析:设计一个文本框和按钮,当点击按钮的时候,会进行随机生成验证码,在指定的时间范围内是不能够重复提交的,按钮会被禁用,当将验证码输入到文本框内,会进行校验是否正确
- 设计思路:通过封装函数,随机获取数组多个元素,转换为字符串,正则拼接切割,当点击按钮的时候,触发倒计时禁用函数,防止重复点击提交,最后获取输入文本框的验证码与随机生成的验证码进行校验匹配,并给出相应的提示
- 实现代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="text" id="txt"/>
<button id="btn">点击发送短信</button>
<div id="info"></div>
</body>
</html>
<script>
var random_arr = ['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'];
var text = document.getElementById("txt");
var info = document.getElementById("info");
btn.onclick = function(){
var n1 = getRandomArrayElements(random_arr,5);
var n2 = n1.toString();
var n3 = n2.replace(/,/g,"");
alert("您的验证码为"+n3+",请输入到文本框中");
btn.disabled = true;
var time = 8;
var timer = setInterval(fn1,1000);
function fn1(){
time--;
if(time>=0) {
btn.innerHTML = time + "s后重新发送";
}else{
btn.innerHTML = "点击发送短信";
btn.disabled = false;
clearTimeout(timer);
time = 8;
}
}
text.onblur = function(){
if(n3 === text.value){
info.innerHTML = "输入正确";
info.style.color = "green";
}else{
info.innerHTML = "输入错误";
info.style.color = "red";
}
}
};
function getRandomArrayElements(arr, count) {
var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}
</script>