A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 李盼盼老师 于 2018-3-21 21:51 编辑


【简介】

      jquery倒计时按钮代码,常用于验证码倒计时按钮,代码效果就是点击按钮以后按钮上面会出现倒计时读数,倒计时的时间可以自行指定,按钮倒计时的格式有4中格式可选。倒计时代码依赖jquery,因为里面有些节点操作是直接用的jq方法,注册自定义事件也是用的jq方法,jquery确实是个非常棒的js库。【效果演示图】
snipaste_20180321_213906.png snipaste_20180321_214410.png

【html代码】
[HTML] 纯文本查看 复制代码
<h3>使用演示 显示为 秒</h3>
<p style="margin-bottom: 40px;">
    <button type="button" id="test1">获取验证码</button>
    <button type="button" id="test1-clear">清理验证码</button>
</p>
<h3>使用演示 显示为 分:秒</h3>
<p style="margin-bottom: 40px;">
    <button type="button" id="test2">获取验证码</button>
</p>
<h3>使用演示 显示为 天:时:分:秒</h3>
<p style="margin-bottom: 40px;">
    <button type="button" id="test3">获取验证码</button>
</p>
<h3>使用演示 显示为 天:时:分:秒</h3>
<p style="margin-bottom: 40px;">
    <button type="button" id="test4">获取验证码</button>
</p>

【js代码】
[JavaScript] 纯文本查看 复制代码
[/font][/color]
[color=#608b4e][font=Consolas]//使用演示 显示为 秒[/font][/color]
[color=#d4d4d4][font=Consolas, &quot;]$("#test1").on("click",function(){
    buttonCountdown($(this), 1000 * 60 * 3, "ss");
}); 
//使用演示 显示为 分:秒
$("#test2").on("click",function(){
    buttonCountdown($(this), 1000 * 60 * 3, "m:s");
});
//使用演示 显示为 时:分:秒
$("#test3").on("click",function(){
    buttonCountdown($(this), 1000 * 60 * 3, "h:m:s");
}); 
//使用演示 显示为 天:时:分:秒
$("#test4").on("click",function(){
    buttonCountdown($(this), 1000 * 60 * 3, "d:h:m:s");
});
//清理$("#test1")的倒计时  比如请求出错或者什么原因要清理倒计时按钮
$("#test1-clear").on("click",function(){
    $("#test1").trigger("bc.clear");
});

【倒计时函数代码】
[JavaScript] 纯文本查看 复制代码
function buttonCountdown($el, msNum, timeFormat) {
    var text = $el.data("text") || $el.text(),
            timer = 0;
    $el.prop("disabled", true).addClass("disabled")
            .on("bc.clear", function () {
                clearTime();
            });

    (function countdown() {
        var time = showTime(msNum)[timeFormat];
        $el.text(time + '后失效');
        if (msNum <= 0) {
            msNum = 0;
            clearTime();
        } else {
            msNum -= 1000;
            timer = setTimeout(arguments.callee, 1000);
        }
    })();

    function clearTime() {
        clearTimeout(timer);
        $el.prop("disabled", false).removeClass("disabled").text(text);
    }

    function showTime(ms) {
        var d = Math.floor(ms / 1000 / 60 / 60 / 24),
                h = Math.floor(ms / 1000 / 60 / 60 % 24),
                m = Math.floor(ms / 1000 / 60 % 60),
                s = Math.floor(ms / 1000 % 60),
                ss = Math.floor(ms / 1000);

        return {
            d: d + "天",
            h: h + "小时",
            m: m + "分",
            ss: ss + "秒",
            "d:h:m:s": d + "天" + h + "小时" + m + "分" + s + "秒",
            "h:m:s": h + "小时" + m + "分" + s + "秒",
            "m:s": m + "分" + s + "秒"
        };
    }

    return this;
}






0 个回复

您需要登录后才可以回帖 登录 | 加入黑马