前端之jQuery示例补充

一 验证码倒计时

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>注册</title>
</head>
<body>
<button id="getVerificationCode">获取验证码</button>

<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
    $('#getVerificationCode').on('click', function () {
        this.disabled = true;
        var countDown = 60;
        var displayTime;
        var that = this;
        var timer = setInterval(function () {
            if (countDown > 0) {
                displayTime = countDown >= 10 ? countDown : '0' + countDown;
                $(that).text(displayTime + '秒后重新获取');
                countDown--;
            } else if (countDown === 0) {
                $(that).text('获取验证码');
                clearInterval(timer);
                that.disabled = false;
            }
        }, 1000)
    })
</script>
</body>
</html>

为什么使用botton标签?

一开始用的是div标签,发现一直点击的话会出现闪烁重置情况,很坑。后面联想到button有disabled的属性,可以在点击时赋值为true,时间到了重新再赋值为false。这样就能解决点击闪烁重置的问题了。

二 倒计时

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>倒计时</title>
    <style>
        #i1{
            color: red;
            padding-left: 10px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
<p>输入倒计时时间(秒):<input id="countDown" type="text"><span id="i1" class="hide">请输入时间</span></p>
<p id="startTiming">00:00:00:00</p>
<button id="start">开始</button>
<button id="end">结束</button>

<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
    var timer;

    $("#start").on('click', function () {
        var countDown = $("#countDown").val();
        if (countDown){
            $("#i1").addClass('hide');
            timer = setInterval(function () {
            var day = 0,
                hour = 0,
                minute = 0,
                second = 0;
            if (countDown > 0) {
                day = Math.floor(countDown / (60 * 60 * 24));
                hour = Math.floor(countDown / (60 * 60)) - (day * 24);
                minute = Math.floor(countDown / 60) - (day * 24 * 60) - (hour * 60);
                second = Math.floor(countDown) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
            }
            if (day <= 9) day = '0' + day;
            if (hour <= 9) hour = '0' + hour;
            if (minute <= 9) minute = '0' + minute;
            if (second <= 9) second = '0' + second;
            $('#startTiming').html(day + ":" + hour + ":" + minute + ":" + second);
            countDown--;
        }, 1000);
        }
        else {
            $("#i1").removeClass('hide');
        }
    });

    $("#end").on('click', function () {
        $("#countDown").val('');
        $('#startTiming').html('00:00:00:00');
        clearInterval(timer);
    });

</script>
</body>
</html>
posted @ 2020-02-25 17:14  Joe1991  阅读(71)  评论(0)    收藏  举报