原生JS - 簡單的時分秒倒計
阿新 • • 發佈:2019-01-11
效果圖
程式碼片 直接copy就可以呼叫
<div id="timer"></div>
setInterval("leftTimer(2020,1,1,00,00,00)", 1000);
//倒計時
function leftTimer(year, month, day, hour, minute, second) {
var leftTime = (new Date(year, month - 1, day, hour, minute, second)) - (new Date()); //計算剩餘的毫秒數
var days = parseInt (leftTime / 1000 / 60 / 60 / 24, 10); //計算剩餘的天數
var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //計算剩餘的小時
var minutes = parseInt(leftTime / 1000 / 60 % 60, 10); //計算剩餘的分鐘
var seconds = parseInt(leftTime / 1000 % 60, 10); //計算剩餘的秒數
days = checkTime(days);
hours = checkTime(hours);
minutes = checkTime(minutes) ;
seconds = checkTime(seconds);
document.getElementById("timer").innerHTML = days + "天" + hours + "小時" + minutes + "分" + seconds + "秒";
}
function checkTime(i) { //將0-9的數字前面加上0,例1變為01
if(i < 10) {
i = "0" + i;
}
return i;
}