按时分秒倒计时、且获取服务器时间、且可以同时多个倒计时

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>按时分秒</title>
  <script src="http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <style type="text/css">
        *{padding:0;margin:0;}
        body{font-size:16px;}
        .timeBox{color:#6dbec5;margin:10px auto;}
        .time{border: 1px solid #6dbec5;width: 40px;height: 20px;text-align: center; line-height: 20px;display: inline-block;}
    </style>
</head>
<body>
    <div class="timeBox" data-times="2017-3-16,12:00:00">
        距结束
        <span class="time date">00</span><span class="time hour">00</span> : <span class="time minutes">00</span> : <span class="time seconds">00</span>
    </div>
    <!--<div class="timeBox" data-times="2016/10/10,10:59:59">
        距结束
        <span class="time date">00</span> 天 <span class="time hour">00</span> : <span class="time minutes">00</span> : <span class="time seconds">00</span>
    </div>-->
</body>

<script type="text/javascript">
var endtime,nowtime,lefttime,d,h,m,s;
$.fn.countDown = function(){
    var _this = $(this);
    _this.each(function(index, el){
        var thisObj = $(this);
        var times = thisObj.data("times");//获得timeBox的data值,即结束时间
        endtime = new Date(times);//把data值转换成时间
       // nowtime = new Date();//获得当前时间
        nowtime = getServerDate();//获得服务器时间
        lefttime=parseInt((endtime.getTime()-nowtime.getTime())/1000); //结束时间-当前时间得到毫秒数,再除以1000得到两个时间相差的秒数
        d=parseInt(lefttime/3600/24);
        h=parseInt((lefttime/3600)%24);
        m=parseInt((lefttime/60)%60);
        s=parseInt(lefttime%60);
        // 三目运算符
        d = d < 10 ? "0"+ d : d;
        h = h < 10 ? "0"+ h : h;
        m = m < 10 ? "0"+ m : m;
        s = s < 10 ? "0"+ s : s;

        if(lefttime<=0){
            d = h = m = s = "00";
            clearInterval(sh);
            location.reload();
        }
        thisObj.find(".date").text(d);
        thisObj.find(".hour").text(h);
        thisObj.find(".minutes").text(m);
        thisObj.find(".seconds").text(s);
    });
}

var sh;
// 调用
sh=setInterval(function(){
    $(".timeBox").countDown();
},1000);

function getServerDate(){
    return new Date($.ajax({async:false}).getResponseHeader("Date"));
}
</script>
</html>

总结:
1、倒计时完成之后记得location.reload();刷新页面。
2、如果倒计时用于活动开始倒计时,就必须获取服务器时间getServerDate(),不然就会出现每个人手机时间不一样,倒计时也就不同,那就尴尬了。
3、new Date()是获取当前系统的时间,getServerDate()就是获取服务器时间。
参考资料:
http://www.cnblogs.com/hellobook/p/6112182.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值