正文  电脑教程 > 服务器教程 >

JS如何设置手机验证码60s等待实现代码

html: <div class="input"> <input class="tel input_all" type="text" name...

html:

<div class="input">
  <input class="tel input_all" type="text" name="tel" placeholder="手机号">
</div>
<div class="input huoqu">
  <input class="yzm input_all" type="text" name="code" placeholder="验证码">
  <button class="btn1">获取验证码</button>
</div>
<span class="error"></span>

JavaScript:

var btn1 = document.querySelector(‘.btn1‘);
var tel = document.querySelector(‘.tel‘);
var error = document.querySelector(‘.error‘);
var time = 60;
btn1.onclick = function(){
  var name = tel.value;  
  if (name == "") {
    error.innerHTML=‘手机号不能为空!‘;
    return;
  } 
  else {
    if (!(/^1[3|4|5|7|8]d{9}$/.test(name))) {
      error.innerHTML=‘手机号格式有误.‘;
       return;
    }
  }
  var timer = setInterval(function(){    
    time--;
    btn1.innerHTML = time + "秒";
    btn1.disabled = true;
    if (time==0) {
      time = 60;
      clearInterval(timer); 
      btn1.innerHTML = "获取验证码";
      btn1.disabled = false;
    }
  },1000);
}