HTML通用组件模板:获取验证码60s倒计时后重新获取
需求:常见的用于登陆验证中,输入电话号码后点击“获取验证码”,开始60s倒计时,这段时间内获取验证码按钮无法点击,60s倒计时结束后,方可“重新获取”。
解析:使用setTime定时器,每秒刷新一次。
案例:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<form>
<div><label for=""><input maxlength="11" type="tel" placeholder="请输入手机号码" /></label>
<input class="veriCode-btn greenbg" type="button" value="获取验证码" /></div>
<div><input type="number" placeholder="请输入验证码" /></div>
<button class="greenbg">确 定</button>
</form>
/*reset*/
input{
border:none;
}
button{border:none;outline:none;}
/*原子类*/
.greenbg{background: rgb(49,189,72);color:#fff;}
.graybg{color:#fff;background:#DDDDDD;}
/*样式*/
form input::-webkit-input-placeholder {
color: rgb(179,179,179);
}
form input:-moz-placeholder {
color: rgb(179,179,179);
}
form input::-moz-placeholder {
color: rgb(179,179,179);
}
form input:-ms-input-placeholder {
color: rgb(179,179,179);
}
form{
width:80%;
text-align:center;
margin:0 auto;
background:#fff;
padding:5%;
border:1px solid #ccc;
border-radius:10px;
}
form>button{
font-size: 16px;
padding:3% 15%;
margin:15% 0 3% 0;
border-radius:5px;
letter-spacing: 2px;
}
form>div{
width:100%;
overflow: hidden;
padding:8% 0 2% 0;
}
form>div *{
float:left;
font-size: 15px;
}
form>div:first-of-type{
border-bottom:1px solid rgb(179,179,179);
}
form>div:first-of-type>label{
width:50%;
margin-top:2%;
}
form>div:first-of-type>input{
float:right;
}
.veriCode-btn{
padding:2% 4%;
border-radius:4px;
}
JS:
$(function(){
/*点击获取验证码,显示”发送中(60)“*/
$(".veriCode-btn").click(function(){
setTime(this);
});
/*验证码倒计时函数(这里演示初始化为5,实际应用中一般为60)*/
var countDown = 5;
function setTime(obj){
if(countDown == -1){
obj.removeAttribute("disabled");
obj.classList.remove("graybg");
obj.classList.add("greenbg");
obj.value = "重新获取";
countDown = 5;
return;
}else{
obj.setAttribute("disabled",true);
obj.classList.remove("greenbg");
obj.classList.add("graybg");
obj.value = "发送中(" + countDown + "s)";
countDown--;
}
setTimeout(function(){setTime(obj);},1000); //循环调用
}
});