DIV CSS 佈局教程網

特殊節日提示功能的實作方法
編輯:關於JavaScript     

概述

開發網站時,在頁面上顯示系統日期相當常見;若在顯示日期的同時一併提示當天節日,還能為訪客帶來便利與溫度。本文示範如何實作這樣一個特殊日期提示功能。

技術要點

(1)建立 Date() 物件實例,透過 getFullYear()、getMonth()、getDate()、getDay() 取得年、月、日、星期等資訊。
(2)getMonth() 取得的是從 0 起算的月份,因此需將結果加 1。
(3)getDay() 回傳的是數值型星期,需用 Array 對照表轉為對應文字。
(4)依月份與日期判斷要顯示的節日名稱。
(5)將資料組合後,透過 <div> 的 innerHTML 輸出到頁面。

具體實作

(1)撰寫 datePrompt() 函式,用於組合日期並顯示節日提示:

<SCRIPT language="javascript">
function datePrompt(){
  calendar = new Date();          // 取得日期物件
  day = calendar.getDay();
  month = calendar.getMonth() + 1; // 取得月(補 1)
  date = calendar.getDate();       // 取得日
  year = calendar.getFullYear();   // 取得四位年份
  var dayname = new Array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
  var time = year + "年" + month + "月" + date + "日 " + dayname[day] + " ";
  var holiday = "";
  if ((month == 1) && (date == 1))  holiday = "<font color=red>元旦";
  if ((month == 5) && (date == 1))  holiday = "<font color=red>國際勞動節";
  if ((month == 5) && (date == 4))  holiday = "<font color=red>青年節";
  if ((month == 6) && (date == 1))  holiday = "<font color=red>國際兒童節";
  if ((month == 7) && (date == 1))  holiday = "<font color=red>建黨紀念日";
  if ((month == 8) && (date == 1))  holiday = "<font color=red>建軍節";
  if ((month == 10) && (date == 1)) holiday = "<font color=red>國慶節";
  if ((month == 12) && (date == 25)) holiday = "<font color=red>聖誕節";
  time = time + holiday;
  clock.innerHTML = time;          // 顯示日期並提示節日
}
//-->
</SCRIPT>

(2)在需要顯示的頁面中,於 <body> 的 onLoad 事件呼叫 datePrompt(),並在適當位置放入 id 為 clock 的 <div>:

<body onLoad="datePrompt()">
<td width="219" height="27" align="center" background="images/1.JPG"><div id="clock"> </div></td>

如此一來,頁面載入時便會自動顯示當天日期、星期與對應節日。若日後想擴充更多節日,只需在判斷區塊中追加條件即可,維護相當容易。

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