00时 00分 00秒

JS倒计时、计时

倒计时

倒计时常用于发送验证码

前端代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>倒计时、计时</title>
</head>
<body>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<input type="text" id="phoneId" name="phone" placeholder="填写手机号">
<button type="button" id="sendVerifyCodeId" style="height: 46px;">获取验证码</button>
<script>
    $(document).ready(function() {
        // 查看js是否被引入
        console.log( "JS引入成功" );
    });

    // 发送验证码
    var clock = "";
    var countDown = 5; // 倒计时采用的秒数,测试可以用5,6这样的小一点的数字,线上一般用60
    var seconds = countDown;
    var $getVerifyCodeButton;
    $( "#sendVerifyCodeId" ).click(function() {
        $getVerifyCodeButton = $( this );
        var mobile =  $.trim($( "#phoneId" ).val());
        var patPhone = /^1\d{10}$/;
        if(mobile == "" || !patPhone.test(mobile)) {
            // 这里用于校验手机号码是否有误,暂时放空不演示
        }
        $getVerifyCodeButton.attr( "disabled", true );
        $getVerifyCodeButton.text("重新获取(" + seconds + "s)");
        clock = setInterval(doLoop, 1000); 
    });

    function doLoop() {
        seconds--;
        if(seconds > 0) {
            $getVerifyCodeButton.text("重新获取(" + seconds + "s)");
        } else {
            clearInterval(clock); //清除js定时器
            $getVerifyCodeButton.attr( "disabled", false );
            $getVerifyCodeButton.text( "获取验证码") ;
            seconds = countDown; //重置时间
        }
    }
</script>
</body>
</html>

计时

计时代码可参照倒计时,也可以查看本博客页面中计时源码

效果如下:

 

posted @ 2018-05-06 17:56  杰克思勒(Jacksile)  阅读(250)  评论(0编辑  收藏  举报