示例:
剩余天数:08天02事02分02秒
html代码:
<div id="timer" data-timer="20160628140203" style="font-size:20px">
剩余天数:
<span id="timer_d">0</span>天
<span id="timer_h">0</span>时
<span id="timer_m">0</span>分
<span id="timer_s">0</span>秒
</div>
js代码:
timer('timer');//调用方法 //时分秒倒计时方法
function timer(eleId){
var element=document.getElementById(eleId);
if(element){
endTimer=element.getAttribute('data-timer');
var endTime=new Date(parseInt(endTimer.substr(0,4), 10),parseInt(endTimer.substr(4,2), 10),parseInt(endTimer.substr(6,2), 10),parseInt(endTimer.substr(8,2), 10),parseInt(endTimer.substr(10,2), 10),parseInt(endTimer.substr(12,2), 10));
var endTimeMonth=endTime.getMonth()-1;
endTime.setMonth(endTimeMonth);
var ts = endTime - new Date();
if(ts>0){
var dd = parseInt(ts / 1000 / 60 / 60 / 24, 10);
var hh = parseInt(ts / 1000 / 60 / 60 % 24, 10);
var mm = parseInt(ts / 1000 / 60 % 60, 10);
var ss = parseInt(ts / 1000 % 60, 10);
dd = dd<10?("0" + dd):dd; //天
hh = hh<10?("0" + hh):hh; //时
mm = mm<10?("0" + mm):mm; //分
ss = ss<10?("0" + ss):ss; //秒
document.getElementById("timer_d").innerHTML=dd;
document.getElementById("timer_h").innerHTML=hh;
document.getElementById("timer_m").innerHTML=mm;
document.getElementById("timer_s").innerHTML=ss;
setTimeout(function(){timer(eleId);},1000);
}else{
document.getElementById("timer_d").innerHTML=0;
document.getElementById("timer_h").innerHTML=0;
document.getElementById("timer_m").innerHTML=0;
document.getElementById("timer_s").innerHTML=0;
}
}
}
原文地址:http://blog.csdn.net/xw505501936/article/details/51554835