js 获取验证码计时器

效果图:

贴上代码:

 <div class="logintitle">
            <input type="tel" id="mobile" name="mobile" maxlength="11" value="" placeholder="请输入手机号">
            <button class="codebutton" onclick="getCode()" id="getcode">获取验证码</button>
  </div>
var timer=60;//全局倒计时 
//获取短信验证码
    function getCode(){
        var mobile=$('#mobile').val();//手机号
        if(!mobile){
            alert('手机号码不能为空!');
            return;
        }
        if(!/^([1-9])\d{10}$/.test(mobile)){
            alert('请输入正确的手机号码!');
            return;
        }
        jQuery.post(url,{//url:获取短信接口地址
            mobile:mobile    //所需参数
        },function(res){
            if(res.status==1){//正常
                countdown();
            }else{
                alert('网络异常,请稍后重新获取验证码!');
                return;
            }
        })
    }
    // 计时器
    function countdown(){
        $('#getcode').attr("disabled", true);
        timer--;
        $('#getcode').text("重新发送(" + timer + ")");
        if(timer <= 0){
            $('#getcode').removeAttr("disabled");
            $('#getcode').text("获取验证码");
            timer = 60;
            return;
        }else{
            setTimeout(function() {
                countdown();
            },1000);
        }      
    }

猜你喜欢

转载自www.cnblogs.com/zhengyeye/p/9881316.html