特意貼出這段代碼,因?yàn)樗拇a簡(jiǎn)潔和清晰,覺(jué)得不錯(cuò),供大家分享。
×××××××函數(shù)定義部分
代碼如下:
<script type="text/javascript">
var $ = function (id) {
return "string" == typeof id ? document.getElementById(id) : id;
};
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
var Extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
var Calendar = Class.create();
Calendar.prototype = {
initialize: function(container, options) {
this.Container = $(container);//容器(table結(jié)構(gòu))
this.Days = [];//日期對(duì)象列表
this.SetOptions(options);
this.Year = this.options.Year || new Date().getFullYear();
this.Month = this.options.Month || new Date().getMonth() + 1;
this.SelectDay = this.options.SelectDay ? new Date(this.options.SelectDay) : null;
this.onSelectDay = this.options.onSelectDay;
this.onToday = this.options.onToday;
this.onFinish = this.options.onFinish;
this.Draw();
},
//設(shè)置默認(rèn)屬性
SetOptions: function(options) {
this.options = {//默認(rèn)值
Year: 0,//顯示年
Month: 0,//顯示月
SelectDay: null,//選擇日期
onSelectDay: function(){},//在選擇日期觸發(fā)
onToday: function(){},//在當(dāng)天日期觸發(fā)
onFinish: function(){}//日歷畫(huà)完后觸發(fā)
};
Extend(this.options, options || {});
},
//當(dāng)前月
NowMonth: function() {
this.PreDraw(new Date());
},
//上一月
PreMonth: function() {
this.PreDraw(new Date(this.Year, this.Month - 2, 1));
},
//下一月
NextMonth: function() {
this.PreDraw(new Date(this.Year, this.Month, 1));
},
//上一年
PreYear: function() {
this.PreDraw(new Date(this.Year - 1, this.Month - 1, 1));
},
//下一年
NextYear: function() {
this.PreDraw(new Date(this.Year + 1, this.Month - 1, 1));
},
//根據(jù)日期畫(huà)日歷
PreDraw: function(date) {
//再設(shè)置屬性
this.Year = date.getFullYear(); this.Month = date.getMonth() + 1;
//重新畫(huà)日歷
this.Draw();
},
//畫(huà)日歷
Draw: function() {
//用來(lái)保存日期列表
var arr = [];
//用當(dāng)月第一天在一周中的日期值作為當(dāng)月離第一天的天數(shù)
for(var i = 1, firstDay = new Date(this.Year, this.Month - 1, 1).getDay(); i <= firstDay; i++){ arr.push(0); }
//用當(dāng)月最后一天在一個(gè)月中的日期值作為當(dāng)月的天數(shù)
for(var i = 1, monthDay = new Date(this.Year, this.Month, 0).getDate(); i <= monthDay; i++){ arr.push(i); }
//清空原來(lái)的日期對(duì)象列表
this.Days = [];
//插入日期
var frag = document.createDocumentFragment();
while(arr.length){
//每個(gè)星期插入一個(gè)tr
var row = document.createElement("tr");
//每個(gè)星期有7天
for(var i = 1; i <= 7; i++){
var cell = document.createElement("td"); cell.innerHTML = " ";