var _$ = function (id) { return "string" == typeof id ? document.getelementbyid(id) : id; }; var class = { create: function() { return function() { this.initialize.apply(this, arguments); } } } object.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结构) this.days = [];//日期对象列表 this.setoptions(options); this.year = this.options.year; this.month = this.options.month; 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(); }, //设置默认属性 setoptions: function(options) { this.options = {//默认值 year: new date().getfullyear(),//显示年 month: new date().getmonth() + 1,//显示月 selectday: null,//选择日期 onselectday: function(){},//在选择日期触发 ontoday: function(){},//在当天日期触发 onfinish: function(){}//日历画完后触发 }; object.extend(this.options, options || {}); }, //上一个月 premonth: function() { //先取得上一个月的日期对象 var d = new date(this.year, this.month - 2, 1); //再设置属性 this.year = d.getfullyear(); this.month = d.getmonth() + 1; //重新画日历 this.draw(); }, //下一个月 nextmonth: function() { var d = new date(this.year, this.month, 1); this.year = d.getfullyear(); this.month = d.getmonth() + 1; this.draw(); }, //画日历 draw: function() { //用来保存日期列表 var arr = []; //用当月第一天在一周中的日期值作为当月离第一天的天数 for(var i = 1, firstday = new date(this.year, this.month - 1, 1).getday(); i <= firstday; i++){ arr.push(" "); } //用当月最后一天在一个月中的日期值作为当月的天数 for(var i = 1, monthday = new date(this.year, this.month, 0).getdate(); i <= monthday; i++){ arr.push(i); } var frag = document.createdocumentfragment(); this.days = []; while(arr.length > 0){ //每个星期插入一个tr var row = document.createelement("tr"); //每个星期有7天 for(var i = 1; i <= 7; i++){ var cell = document.createelement("td"); cell.innerhtml = " "; if(arr.length > 0){ var d = arr.shift(); cell.innerhtml = d; if(d > 0){ this.days[d] = cell; //判断是否今日 if(this.issame(new date(this.year, this.month - 1, d), new date())){ this.ontoday(cell); } //判断是否选择日期 if(this.selectday && this.issame(new date(this.year, this.month - 1, d), this.selectday)){ this.onselectday(cell); } } } row.appendchild(cell); } frag.appendchild(row); } //先清空内容再插入(ie的table不能用innerhtml) while(this.container.haschildnodes()){ this.container.removechild(this.container.firstchild); } this.container.appendchild(frag); this.onfinish(); }, //判断是否同一日 issame: function(d1, d2) { return (d1.getfullyear() == d2.getfullyear() && d1.getmonth() == d2.getmonth() && d1.getdate() == d2.getdate()); } };