//主方法 function xxx(){ //獲取2個時間,一個是當前時間,一個是活動開始時間。而後傳到getTimeOutMix方法中, //currentTime傳過來的時候就是毫秒,startTimeStr時間是xxxx/hh/mm/ss 00:00:00格式 var timeOutMis = getTimeOutMis(currentTime,startTimeStr); var serverTimeArray = []; serverTimeArray.push(timeOutMis); countdown(serverTimeArray); } function getTimeOutMis(currentTime,startTimeStr) { var startTime = 0; if(startTimeStr != null || startTimeStr != '') { //把startTimeStr的格式轉換爲毫秒 startTime = Date.parse(new Date(startTimeStr)); } console.log(currentTime+ '==' + startTimeStr); console.log(currentTime+ '==' + startTime); var timeVal = startTime - currentTime; console.log(timeVal); return timeVal; } function countdown(time_distance) { //var $timer = $(".js_countdown"); // if ( $timer.size() < 0 || !isArray($timer)) { /* if ( $timer.size() < 0 || !isArray($timer)) { return; } */ var $timer = $(".js_countdown"); if ( $timer.size() < 0 || !isArray(time_distance)) { return; } $timer.each(function(e) { var time_arry = time_distance[e]; var me = $(this); main(time_arry,me); }); function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } function main(time_arry,elem) { if (time_arry >= 0) { var int_day, int_hour, int_minute, int_second; var timeDown = time_arry,timerID; //int_day = Math.floor(timeDown / 86400000); //timeDown -= int_day * 86400000; int_hour = Math.floor(timeDown / 3600000); timeDown -= int_hour * 3600000; int_minute = Math.floor(timeDown / 60000); timeDown -= int_minute * 60000; int_second = Math.floor(timeDown / 1000); //int_day = int_day < 10 ? "0" + int_day : int_day; int_hour = int_hour < 10 ? "0" + int_hour : int_hour; int_minute = int_minute < 10 ? "0" + int_minute : int_minute; int_second = int_second < 10 ? "0" + int_second : int_second; if(int_hour >=999) { int_hour = 999; } //把時,分,秒設置到頁面class=count_hour,count_min,count_sec的元素上去 //elem.find(".day").text(int_day); elem.find(".count_hour").text(int_hour); elem.find(".count_min").text(int_minute); elem.find(".count_sec").text(int_second); //倒計時結束 重置計時器 if (parseInt(int_hour) == 0 && parseInt(int_minute) == 0 && parseInt(int_second) == 0) { clearTimeout(timerID); return; } time_arry -= 1000; timerID = setTimeout(function() { main(time_arry,elem); }, 1000); } else { clearTimeout(timerID); } } // main(); }
簡單來講,過程是。計算2個時間的時間差。先把2個時間轉換爲毫秒,再相減。這個結果是倒計時的時間。this
而後再把這個結果轉換爲日,時,分,秒,就行了prototype