最近趕完專案終於鬆一口氣,閒下來翻了翻日期相關的函式,順手就寫了個日曆控制項。功能是最基礎的版本,但把「怎麼算出該月第一天落在星期幾」這件事走過一遍,對 Date 的認識會清楚很多。
var date = new Date(); date.getFullYear(); // 完整年份,例如 2015 date.getMonth(); // 月份索引 0~11,所以要 +1 date.getDate(); // 當月幾號,1~31 date.getDay(); // 星期幾,0=週日 … 6=週六
該月第一天是星期幾——決定第一列要空幾格:
var getWeekDay = function (year, month, day) {
var date = new Date(year, month, day);
return date.getDay();
};
var weekstart = getWeekDay(this.year, this.month - 1, 1);
該月總共有幾天——這裡用了一個小技巧:把「日」傳 0,就會得到上個月的最後一天:
var getMonthDays = function (year, month) {
var date = new Date(year, month, 0);
return date.getDate();
};
var monthdays = this.getMonthDays(this.year, this.month);
掌握這兩個數字,剩下的就是按 7 個一組把日期填進格子裡。
<html>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<head>
<style type="text/css">
td { text-align: center; }
</style>
<script type="text/javascript">
window.onload = function () {
var Calender = function () {
this.Init.apply(this, arguments);
};
Calender.prototype = {
Init: function (container, options) {
this.date = new Date();
this.year = this.date.getFullYear();
this.month = this.date.getMonth() + 1;
this.day = this.date.getDate();
this.week = this.date.getDay();
this.weekstart = this.getWeekDay(this.year, this.month - 1, 1);
this.monthdays = this.getMonthDays(this.year, this.month);
this.containerDiv = document.getElementById(container);
this.options = options != null ? options : {
border: '1px solid green',
width: '400px',
height: '200px',
backgroundColor: 'lightgrey',
fontColor: 'blue'
};
},
getMonthDays: function (year, month) {
return new Date(year, month, 0).getDate();
},
getWeekDay: function (year, month, day) {
return new Date(year, month, day).getDay();
},
View: function () {
var tablestr = '<table>';
tablestr += '<tr><td colspan="3"></td><td>年:' + this.year
+ '</td><td colspan="3">月:' + this.month + '</td></tr>';
tablestr += '<tr><td width="14%">日</td><td width="14%">一</td>'
+ '<td width="14%">二</td><td width="14%">三</td>'
+ '<td width="14%">四</td><td width="14%">五</td>'
+ '<td width="14%">六</td></tr>';
var index = 1;
var style = '';
// 第一列:先墊空白格,再放日期
if (this.weekstart < 7) {
tablestr += '<tr>';
for (var i = 0; i < this.weekstart; i++) {
tablestr += '<td></td>';
}
for (var i = 0; i < 7 - this.weekstart; i++) {
style = this.day == (i + 1) ? "background-Color:green;" : "";
index++;
tablestr += '<td style="' + style + '" val='
+ (this.year + '-' + this.month + '-' + (i + 1))
+ '>' + (i + 1) + '</td>';
}
tablestr += '</tr>';
}
// 中間:完整的整列
var remaindays = this.monthdays - (7 - this.weekstart);
var count = Math.floor(remaindays / 7);
for (var i = 0; i < count; i++) {
tablestr += '<tr>';
for (var k = 0; k < 7; k++) {
style = this.day == (index + k) ? "background-Color:green;" : "";
tablestr += '<td style="' + style + '" val='
+ (this.year + '-' + this.month + '-' + (index + k))
+ '>' + (index + k) + '</td>';
}
tablestr += '</tr>';
index += 7;
}
// 最後一列:不滿一週的尾數
var remaincols = this.monthdays - (index - 1);
tablestr += '<tr>';
for (var i = 0; i < remaincols; i++) {
style = this.day == index ? "background-Color:green;" : "";
tablestr += '<td style="' + style + '" val='
+ (this.year + '-' + this.month + '-' + index)
+ '>' + index + '</td>';
index++;
}
tablestr += '</tr>';
tablestr += '</table>';
return tablestr;
},
Render: function () {
var that = this;
var calenderDiv = document.createElement('div');
calenderDiv.style.border = this.options.border;
calenderDiv.style.width = this.options.width;
calenderDiv.style.height = this.options.height;
calenderDiv.style.cursor = 'pointer';
calenderDiv.style.backgroundColor = this.options.backgroundColor;
calenderDiv.style.color = 'red';
calenderDiv.innerHTML = this.View();
// 事件委派:點到帶 val 的格子就回報日期
calenderDiv.onclick = function (e) {
var evt = e || window.event;
var target = evt.srcElement || evt.target;
if (target && target.getAttribute('val')) {
alert(target.getAttribute('val'));
}
};
var div = document.createElement('div');
div.appendChild(calenderDiv);
// 重新計算所有日期參數
var resetPara = function (year, month, day) {
that.date = new Date(year, month, day);
that.year = that.date.getFullYear();
that.month = that.date.getMonth() + 1;
that.day = that.date.getDate();
that.week = that.date.getDay();
that.weekstart = that.getWeekDay(that.year, that.month - 1, 1);
that.monthdays = that.getMonthDays(that.year, that.month);
};
// 上一頁 / 下一頁
var pagerDiv = document.createElement('div');
var preBtn = document.createElement('input');
preBtn.type = 'button';
preBtn.value = '<';
preBtn.onclick = function () {
that.containerDiv.removeChild(div);
resetPara(that.year, that.month - 2, that.day);
that.Render();
};
var nextBtn = document.createElement('input');
nextBtn.type = 'button';
nextBtn.value = '>';
nextBtn.onclick = function () {
that.containerDiv.removeChild(div);
resetPara(that.year, that.month, that.day);
that.Render();
};
pagerDiv.appendChild(preBtn);
pagerDiv.appendChild(nextBtn);
div.appendChild(pagerDiv);
// 年 / 月下拉選單
var dropDiv = document.createElement('div');
var dropdivstr = '<select id="ddlYear">';
for (var i = 1900; i <= 2100; i++) {
dropdivstr += i == that.year
? '<option value="' + i + '" selected="true">' + i + '</option>'
: '<option value="' + i + '">' + i + '</option>';
}
dropdivstr += '</select><select id="ddlMonth">';
for (var i = 1; i <= 12; i++) {
dropdivstr += i == that.month
? '<option value="' + i + '" selected="true">' + i + '</option>'
: '<option value="' + i + '">' + i + '</option>';
}
dropdivstr += '</select>';
dropDiv.innerHTML = dropdivstr;
div.appendChild(dropDiv);
that.containerDiv.appendChild(div);
var ddlChange = function () {
var ddlYear = document.getElementById('ddlYear');
var ddlMonth = document.getElementById('ddlMonth');
var year = ddlYear.options[ddlYear.selectedIndex].value;
var month = ddlMonth.options[ddlMonth.selectedIndex].value;
that.containerDiv.removeChild(div);
resetPara(year, month - 1, that.day);
that.Render();
};
document.getElementById('ddlYear').onchange = ddlChange;
document.getElementById('ddlMonth').onchange = ddlChange;
}
};
var calender = new Calender('dvTest', {
border: '1px solid green',
width: '400px',
height: '200px',
backgroundColor: ''
});
calender.Render();
};
</script>
</head>
<body>
<div id="dvTest"</div>
</body>
</html>
用 div 而非 table 屬性排版:原本直接對 table 設定 innerHTML 在 IE 上會出錯(table 的 innerHTML 是唯讀的),所以改成把整張表組好字串再塞進外層 div,避開這個限制。
加入 options 物件:把邊框、寬高、顏色抽成可傳入設定,重用時不必改原始碼。
用事件委派取代逐格綁定:把 click 掛在外層容器上,透過 getAttribute('val') 判斷點到哪一格。這樣每格都是純資料,不需要為每個 td 註冊事件。
修正跨月翻頁:上一頁傳 month - 2 而非 month - 1,是因為 resetPara 内部會再對 getMonth() 加 1;傳 month - 2 才能實質倒退一個月。這種「月份索引」與「人類月份」混用的地方最容易出錯,值得特別留意。
這個版本每次翻頁都整份 removeChild 再重建 DOM,頁面裡若有其他元素用了 ddlYear/ddlMonth 這類常見 id 也會衝突,建議改成 class 或在元件內用 ref 保存節點參照。若要選日期區間、 disable 特定日期、或與表單整合,可以在 View() 產生的 val 屬性上動手腳。真正上 production 時,直接採用成熟套件會省下大量處理邊界條件的時間——手寫一遍主要還是為了把原理吃透。