Hoe's Notes

JQuery实现抢购列表的多个倒计时


可以遍历多个列表。

<div class="list" endTime="1494819200"></div>
<div class="list" endTime="1493809200"></div>
<div class="list" endTime="1494819200"></div>
<div class="list" endTime="1493809200"></div>
<div class="list" endTime="1493974800"></div>

JavaScript部分:

<script src="http://lib.sinaapp.com/js/jquery/1.10/jquery-1.10.0.min.js"></script>
<script language="javascript">
$(function() {
    countdown();
});
//倒计时函数
function countdown() {
    $(".list").each(function() {
        //结束时间字符串
        var endTime = this.getAttribute("endTime");
        // js 的时间戳是毫秒
        var timestamp = Date.parse(new Date()) / 1000;
        // 剩余秒数
        var overplus = endTime - timestamp;
        if (overplus > 0) {
            var day    = Math.floor((overplus / 3600) / 24);
            var hour   = Math.floor((overplus / 3600) % 24);
            var minite = Math.floor((overplus / 60) % 60);
            var second = Math.floor(overplus % 60);
            day    = day    > 0 ? day  + '天' : '';
            hour   = hour   > 0 ? hour + '时' : '';
            minite = minite > 0 ? (minite < 10 ? '0' + minite + '分' : minite + '分') : '';
            second = second > 0 ? (second < 10 ? '0' + second + '秒' : second + '秒') : '';
            $(this).html(day + hour + minite + second);
        } else
            $(this).html("活动已结束!");
    });
    setTimeout("countdown()", 1000);
}
</script>