本文分享一個以 JavaScript 實作的日曆控制元件,包含樣式定義、年月切換、日期選擇、下拉選單與拖曳移動等完整功能。
呼叫範例如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="../JS/connotation.js" type="text/javascript"></script>
<script type="text/javascript">
var c = new Calendar("c");
document.write(c);
</script>
</head>
<body>
<div>
普通調用:<input type="text" name="txt2" onclick="c.showMoreDay = true; c.show(this);" /><br />
<div style="height: 262px"></div>
按鈕調用:<input type="text" name="btntxt" id="btntxt" /><input name="button" value="*" id="button" type="button" onclick="c.showMoreDay = true; c.show(getObjById('btntxt'), '1982-1-1', this)" />
<br />
<input type="text" name="btntxt3" id="btntxt3" /><input name="button3" value="*" id="button3" type="button" onclick="c.showMoreDay = true; c.show(this, getObjById('btntxt3'))" />
</div>
</body>
</html>
所需的 jQuery 檔案(Calendar 類的完整實作):
function Calendar(objName)
{
this.style = {
borderColor : "#909eff", // 邊框顏色
headerBackColor : "#909EFF", // 表頭背景顏色
headerFontColor : "#ffffff", // 表頭字體顏色
bodyBarBackColor : "#f4f4f4", // 日歷標題背景色
bodyBarFontColor : "#000000", // 日歷標題字體色
bodyBackColor : "#ffffff", // 日歷背景色
bodyFontColor : "#000000", // 日歷字體色
bodyHolidayFontColor : "#ff0000", // 假日字體色
watermarkColor : "#d4d4d4", // 背景水印色
moreDayColor : "#cccccc" // 上月/下月日期顏色
};
this.showMoreDay = false; // 是否顯示上月和下月的日期
this.Obj = objName;
this.date = null;
this.mouseOffset = null;
this.dateInput = null;
this.timer = null;
}
Calendar.prototype.toString = function()
{
var str = this.getStyle();
str += '<div Author="alin" class="calendar" style="display:none;" onselectstart="return false" oncontextmenu="return false" id="Calendar">\n';
str += '<div Author="alin" class="cdrWatermark" id="cdrWatermark"></div><div id="cdrBody" style="position:absolute;left:0px;top:0px;z-index:2;width:140px;">';
str += this.getHeader();
str += this.getBody();
str += '</div><div Author="alin" id="cdrMenu" style="position:absolute;left:0px;top:0px;z-index:3;display:none;" onmouseover="' + this.Obj + '.showMenu(null);" onmouseout="' + this.Obj + '.hideMenu();"></div></div>';
return str;
};
類別中還實作了 getStyle(樣式輸出)、getHeader(表頭:年、月切換與上一年/月、下一年/月按鈕)、getBody(六週七列的日期格與「今天」列)、getYearMenu / getMonthMenu(年、月下拉選單)、show / hide(顯示與定位,會自動判斷上下方空間)、bindDate(綁定日期、計算上下月補位與閏年)、getToday、isHoliday(週末判斷)、onChangeYear / onChangeMonth(年月切換並做 1000–9999 範圍檢查)、以及 onMouseOver / onMouseOut / onClick 等互動方法。
輔助函式部分則包含 getObjById、mouseCoords、getPosition、getMouseOffset 與拖曳相關的 dragStart / drag / dragEnd,並為 Number 與 Date 擴充了 NaN0 與 toFormatString 方法,最後透過 document.onclick / onmousedown / onmousemove / onmouseup 綁定「點擊外部關閉日曆」與「拖曳標題列移動日曆」的功能。
整體而言,這個元件透過 this.style 物件集中管理配色,方便自訂主題;並以 showMoreDay 控制是否顯示跨月日期,兼顧了外觀彈性與實用性。