<!doctype html> <html> <head> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <meta charset="UTF-8"> <meta name="format-detection" content="telephone=no" /> <title>无标题文档</title> <style type="text/css"> *{padding:0px;margin:0px;} .countdown{ display: inline-block; font-size:0.56rem; color: #a8a8a8; box-sizing: border-box; } .countdown span{ display: inline-block; 0.92rem; text-align: center; line-height:0.96rem; color: #fff; background: #434343; border-radius: 5px; } </style> </head> <body> <p id="time"></p> <!--<p id="time2"></p> <p id="time3"></p>--> 可以直接调用的方法<br/> <p id="time4" class="countdown"></p> </body> <script type="text/javascript" src="jquery-1.11.3.min.js"></script> <script type="text/javascript"> //1.倒计时调用一次,最初的方法 clock(); function clock() { var deadline= new Date("2018/12/17 12:00:00"); //倒计时 var now = new Date() var diff = -480 - now.getTimezoneOffset() //是北京时间和当地时间的时间差 var leave = (deadline.getTime() - now.getTime()) + diff*60000 var day = Math.floor(leave / (1000 * 60 * 60 * 24)) var hour = Math.floor(leave / (1000*3600)) - (day * 24) var minute = Math.floor(leave / (1000*60)) - (day * 24 *60) - (hour * 60) var second = Math.floor(leave / (1000)) - (day * 24 *60*60) - (hour * 60 * 60) - (minute*60) var str="距离结束时间:"+day+"天"+hour+"小时"+minute+"分"+second +"秒……"; document.getElementById('time').innerHTML=str; //document.getElementById('time2').innerHTML=deadline; //document.getElementById('time3').innerHTML=now; setTimeout("clock()",1000); } //2.改进后带的倒计时,可以同时多个地方调用 /* 如果后台时间给的不太标准的话 比如2018-09-23 12:00需转化为 var liveTime="2018-09-23 12:00"; var times=liveTime+":00"; times=times.replace(/-/g,'/'); 2018/09/23 12:00:00 */ clock2("2018/10/17 12:00:00","#time4"); function clock2(time,doc){ var deadline= new Date(time); //倒计时 var now = new Date() var diff = -480 - now.getTimezoneOffset() //是北京时间和当地时间的时间差 var leave = (deadline.getTime() - now.getTime()) + diff*60000 var day = Math.floor(leave / (1000 * 60 * 60 * 24)) if(day<10){ day='0'+day; } var hour = Math.floor(leave / (1000*3600)) - (day * 24) if(hour<10){ hour='0'+hour; } var minute = Math.floor(leave / (1000*60)) - (day * 24 *60) - (hour * 60) if(minute<10){ minute='0'+minute; } var second = Math.floor(leave / (1000)) - (day * 24 *60*60) - (hour * 60 * 60) - (minute*60) if(second<10){ second='0'+second; } if(leave==0){ var str="倒计时:<span>00</span>:<span>00</span>:<span>00</span>:<span>00</span>"; }else{ var str="倒计时:<span>"+day+"</span>:<span>"+hour+"</span>:<span>"+minute+"</span>:<span>"+second +"</span>"; } $(doc).html(str); setTimeout("clock2('"+time+"','"+doc+"')",1000); } </script> </html>
效果视图:
2018-08-03 16:02:20