【原生js】原生js实现验证码短信发送倒计时

时间:2022-11-18 23:40:36

【原生js】原生js实现验证码短信发送倒计时

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><!--强制以webkit内核来渲染-->
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">
<!--按设备宽度缩放,并且用户不允许手动缩放-->
<meta name="format-detection" content="telephone=no"><!--不显示拨号链接-->
<title>非会员未关注</title>
<link rel="stylesheet" href="css/common.css">
<link rel="stylesheet" href="css/registered.css">
</head>
<body>
<div class="main">
<div class="top"></div>
<div class="form">
<input type="text" placeholder="请输入您的手机号">
<div class="yzm">
<input type="text" class="left"><span class="right getCode">获取验证码</span>
</div>
<div class="btn-xiadan">注册并下单</div>
</div>
</div>
<script>
function getClass(className) {
return document.getElementsByClassName(className)[0];
}
var getCode=getClass('getCode');
var countdown={
timeAll:30,
state:true,
//计时器
clickFun:function (domName) {
countdown.state=false;
var time=setInterval(function () {
domName.innerText="剩余"+countdown.timeAll+"秒";
domName.style.backgroundColor="grey";
countdown.timeAll=countdown.timeAll-1;
if(countdown.timeAll==-1){
clearInterval(time);
domName.innerText="获取验证码";
domName.style.backgroundColor="#f54339";
countdown.timeAll=5;
countdown.state=true;
}
},1000)
}
};
getCode.addEventListener('touchstart',function () {
//防止点击以后还可以继续点击生效加快计时,通过state来判断是否可点击
if(countdown.state){
countdown.clickFun(getCode);
}
},false);
</script>
</body>
</html>

个人博客:[**午后南杂**](http://recoluan.gitlab.io)