DIV CSS 佈局教程網

用 JavaScript 做倒數計時鐘的實作範例
編輯:JavaScript綜合知識     

倒數計時的核心是「目標時間減去現在時間」,再把差額拆解成天、時、分、秒。以下這份範例以倒數到 2008 年北京奧運為題,完整示範了流程。

設定目標日期

<SCRIPT language="JavaScript">
function setcountdown(theyear, themonth, theday) {
    yr = theyear;
    mo = themonth;
    da = theday;
}
setcountdown(2008, 7, 12);

var occasion = "2008北京奧運會";
var message_on_occasion = "盼望已久的時刻終於來到了!";
var countdownwidth = '480px';
var countdownheight = '20px';
var countdownbgcolor = 'tan';
var opentags = '<font face="新細明體"><small>';
var closetags = '</small></font>';
var montharray = new Array("Jan","Feb","Mar","Apr","May","Jun",
                           "Jul","Aug","Sep","Oct","Nov","Dec");
var crosscount = '';

function start_countdown() {
    if (document.getElementById) {
        crosscount = document.getElementById("countdownie");
        countdown();
    }
}

if (document.getElementById)
    document.write('<span id="countdownie" style="width:' + countdownwidth
        + '; background-color:' + countdownbgcolor + '"></span>');

window.onload = start_countdown;

計算差額

把現在時間與目標時間都轉成可相減的形式,再一口氣拆出各單位:

function countdown() {
    var today = new Date();
    var todayy = today.getYear();
    if (todayy < 1000) todayy += 1900;
    var todaym = today.getMonth();
    var todayd = today.getDate();
    var todayh = today.getHours();
    var todaymin = today.getMinutes();
    var todaysec = today.getSeconds();

    var todaystring = montharray[todaym] + " " + todayd + ", " + todayy
                    + " " + todayh + ":" + todaymin + ":" + todaysec;
    var futurestring = montharray[mo - 1] + " " + da + ", " + yr;

    var dd = Date.parse(futurestring) - Date.parse(todaystring);
    var dday  = Math.floor(dd / (60 * 60 * 1000 * 24) * 1);
    var dhour = Math.floor((dd % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
    var dmin  = Math.floor(((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
    var dsec  = Math.floor((((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);

    crosscount.innerHTML = opentags + "還有 " + dday + " 天, " + dhour
        + " 小時, " + dmin + " 分, " + dsec + " 秒 就是 " + occasion + closetags;

    setTimeout("countdown()", 1000);
}
</SCRIPT>

關鍵邏輯說明

這裡有兩個細節值得注意。第一,dd 是毫秒差,用整數除法與取餘數逐層剝離:先除以一天的毫秒數得到天數,剩下的部分再除以一小時的毫秒數得到小時,以此類推。第二,範例中原本針對「時間剛好到點」與「時間已過」各有獨立的分支處理(顯示慶祝訊息或提示已過期),實作時應保留這兩個判斷,否則倒數歸零後會出現負數。

現代寫法的對照

今天要寫同樣的功能,會簡短很多:

function tick() {
    var diff = new Date("2008-07-12T00:00:00") - new Date();
    if (diff <= 0) {
        document.getElementById("cd").textContent = "時間已經過了";
        return;
    }
    var d = Math.floor(diff / 86400000);
    var h = Math.floor(diff / 3600000) % 24;
    var m = Math.floor(diff / 60000) % 60;
    var s = Math.floor(diff / 1000) % 60;
    document.getElementById("cd").textContent = `還有 ${d} 天 ${h} 小時 ${m} 分 ${s} 秒`;
    setTimeout(tick, 1000);
}
tick();

直接讓 Date 的減法處理時區與解析,就不必再手動組字串餵給 Date.parse(),也不容易出錯。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved