跟我做:Javascript 下的日历控件(Calendar)
[私有]
[私有]
[私有]
[私有]
显示控件.
Calendar中的日期.
检查日期合法性.
是否合法.
是否闰年
是否闰年.
获取月的天数
天数.
设置选定日期.
获取选定日期.
月枚举.
周中日枚举.
日历控件 window.currentDay = null; //当前选择日期 window.myTextBox = null; //当前显示日期的控件 window.DayChangedCallback = null;//日历选择日期的回调方法 window.MyCalendarPerforms = null;//激活日历的方法, 通过显示控件的相关事件调用 //日历选择日期的回调方法 DayChangedCallback = function(sender, args){ try{ currentDay = args; myTextBox.value = currentDay.GetText("年", "月", "日");//输出所选日期. 自定义日期序列化. //myCalendar.Hidden();//掩藏控件 } catch(e){ alert(e.message); } } //激活日历的方法 MyCalendarPerforms = function(textBox){ try{ if(myCalendar.IsVisible()) myCalendar.Hidden();//掩藏控件 else{ if(myTextBox.value != '')//注意: myTextBox == textBox currentDay.FromText(myTextBox.value, "年", "月", "日");//获取已有日期. 注意根据日期的格式, 让系统进行反序列. myCalendar.Show(myTextBox, currentDay);//设置日历显示日期. Show(sender, currentDay),
日历将显示在 sender 附近, 初始化时显示 currentDay. } } catch(e){ alert(e.message); } } //日历显示容器 document.write("
"); var pannel = document.getElementById('calendarPannel'); //日期显示绑定的控件 document.write('
'); myTextBox = document.getElementById('myTextBox'); //本地化, 缺省为英文 var months = new CalendarMonths(["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]); var weekdays = new CalendarWeekDays(["日","一","二","三","四","五","六"]); //设置初始日期. 缺省参数则为今天. currentDay = new CalendarDay();//currentDay = new CalendarDay(2008, 5, 12); //创建日历控件. 注意自定义日历显示位置的位移差, 此处用了(5, -150). myCalendar = new Calendar('myCalendar', pannel, DayChangedCallback, 5, -150, currentDay, months, weekdays); } CalendarDemon();//需要额外引用 Tooltip.js </script>
右侧是该控件的示范应用,朋友们可点击试用: | <script type=text/javascript> function Tooltip(pannel, CreateTipCallback, toper, lefter){ /// /// 标签提示类. 使用方法参见示例代码 JsDemons/Html/TooltipDemon.js. /// 请尊重作者劳动, 引用需注明出处. /// Howard.Queen@hotmail.com, 2008-04-24. /// http://howard-queen.cnblogs.com/ /// 2008-07-10 /// 1, 修改 sender.top = [number] 为 sender = [number]px; 完美支持 Firefox. /// /// 提示容器. /// 用以生成提示内容的方法. /// 默认上位移. /// 默认左位移. this._sender = null; this._pannel = null; this._top = null; this._toper = 20; this._left = null; this._lefter = 10; this._Init(pannel, CreateTipCallback, toper, lefter); } Tooltip.prototype = { _Init: function(pannel, CreateTipCallback, toper, lefter){ /// [私有] if(pannel == undefined) throw {name: "ArgumentNullException", message: "提示内容的容器不可为空."}; this._pannel = pannel; this._pannel.style.position = "absolute"; if(CreateTipCallback == undefined) return; this._CreateTipCallback = CreateTipCallback; if(toper == undefined) return; this._toper = toper; if(lefter == undefined) return; this._lefter = lefter; }, _CreateTipCallback: function(sender, args){ /// [私有] return args.toString(); }, IsVisible: function(){ return this._pannel.style.display == 'block'; }, Show: function(sender, args, toper, lefter){ /// 显示提示框. /// 事件者. /// 参数值. /// 上位移. /// 左位移. if(this._sender != sender){ this._sender = sender;//缓存 this._pannel.innerHTML = this._CreateTipCallback(sender, args); this._top = sender.offsetTop + sender.clientHeight + (toper == undefined ? this._toper : toper); this._left= sender.offsetLeft + sender.clientWidth + (lefter == undefined ? this._lefter : lefter); while (sender.offsetParent != null){ sender = sender.offsetParent; this._top += sender.offsetTop; this._left += sender.offsetLeft; } this._pannel.style.top = [this._top, 'px'].join(''); this._pannel.style.left = [this._left, 'px'].join(''); //上面的代码都是将悬浮层调整到指定控件的正下方 //alert('Top: ' + this._pannel.style.top + ' Left: ' + this._pannel.style.left); } this._pannel.style.display = "block"; }, Hidden: function(){ /// 隐藏提示框. this._pannel.style.display = "none"; } } /// function Calendar(Id, pannel, SelectedDayChangedEvent, toper, lefter, selectedDay, calendarMonths, calendarWeekDays){ /// /// 日期选择控件. 月份从 1 开始.使用方法参见示例代码 JsDemons/Html/CalendarDemon.js. /// 参考版本《日期选择 - BY ziyue, By Jiang Hongbin等》. /// /// /// 请尊重作者劳动, 引用需注明出处. /// Howard.Queen@hotmail.com, 2008-07-03. /// http://howard-queen.cnblogs.com/ /// 2008-07-10 /// 1, 修改 node.innerText 为 node.innerHTML. 完美支持 Firefox. /// 2, 添加年份无上下限功能. /// 3, 添加当前所选日期亮显功能. /// 4, 更改了自定义日期序列化与反序列化, 使得更加友好. /// 5, 采用显示缓存策略以提高性能. /// 6, 一些方法的命名更改. /// /// 当前控件名称. /// 显示容器. /// 选择日期更改事件. /// 所选日期. /// 月名称. /// 周中日名称. this._Init(Id, pannel, SelectedDayChangedEvent, toper, lefter, selectedDay, calendarMonths, calendarWeekDays); } Calendar.prototype = { _Init: function(Id, pannel, SelectedDayChangedEvent, toper, lefter, selectedDay, calendarMonths, calendarWeekDays){ this.Id = Id; if(pannel == undefined) throw {name:"ArgumentNullException", message:"参数为空, 参数名 pannel."}; if(SelectedDayChangedEvent == undefined) throw {name:"ArgumentNullException", message:"参数为空, 参数名 SelectedDayChangedEvent."}; this._SelectedDayChangedEvent = SelectedDayChangedEvent;//[私有]日选择已更改事件. this._toolTip = new Tooltip(pannel, this._DrawCallback, toper, lefter);//[私有]显示控件. this._today = new CalendarDay();//[私有]今天. if(selectedDay == undefined)//[私有]当前所选日. this.selectedDay = new CalendarDay(); else this.selectedDay = selectedDay; if(calendarMonths == undefined)//[私有]月名称. this.calendarMonths = new CalendarMonths(); else this.calendarMonths = calendarMonths; if(calendarWeekDays == undefined)//[私有]周中日名称. this.calendarWeekDays = new CalendarWeekDays(); else this.calendarWeekDays = calendarWeekDays; this._yearsSelect= null;//[私有]年选择控件. this._monthsSelect= null;//[私有]月选择控件. this._daysTable= null;//[私有]周、日显示控件. this._currentCell = null; this._currentCellColor = null; }, _DrawCallback: function(sender, args){ /// 回调显示. var temp = new Array(); args._Render(temp); return temp.join(''); }, _Render: function(temp){ /// [私有] temp.push(' '); this._RenderYear(temp); this._RenderMonth(temp); temp.push([' | ', this._today.GetText(), ' | '].join('')); this._RenderWeek(temp); this._RenderDay(temp); temp.push(' |
|
'); }, _RenderYear: function(temp){ ///
[私有] temp.push(["
"].join('')); temp.push([""].join('')); for (var i = this.selectedDay.year - 10; i < this.selectedDay.year + 10; i++) temp.push([""].join('')); temp.push(""); }, _RenderMonth: function(temp){ /// [私有] temp.push([""].join('')); for (var i = 1; i <= this.calendarMonths.List.length; i++) temp.push([" |
"); }, _RenderWeek: function(temp){ /// temp.push("
"); for (var i = 0; i < this.calendarWeekDays.List.length; i++) temp.push(["
", this.calendarWeekDays.List[i], " |
"].join('')); temp.push(" "); }, _RenderDay: function(temp){ /// for (var i = 0; i < 6; i++){ temp.push("
"); for (var j = 0; j < this.calendarWeekDays.List.length; j++) temp.push(["
"].join('')); temp.push(" "); } }, _OnCurrentDayChanging: function(dayCell){ if(this._currentCell != null){ this._currentCell.style.backgroundColor = this._currentCellColor; } this._currentCell = dayCell; this._currentCellColor = dayCell.style.backgroundColor; dayCell.style.backgroundColor = 'yellow'; }, _Refresh: function(year, month) { /// var weekIndex = 1; var dayNumber = 1; var daysCount = this.selectedDay.GetMonthDays(year, month);//月中日数 var dayInWeek = new Date(year, month - 1, 1).getDay();//初始周中日数 //第一行清零 for (var i = 0; i < dayInWeek && i < this._daysTable.rows[weekIndex].cells.length; i++){ this._daysTable.rows[weekIndex].cells[i].innerHTML = ''; } //第一行显示 for (; dayInWeek < this._daysTable.rows[weekIndex].cells.length; dayInWeek++, dayNumber++){ this._daysTable.rows[weekIndex].cells[dayInWeek].innerHTML = dayNumber; } //内容行显示 for (weekIndex ++;dayNumber <= daysCount && weekIndex < this._daysTable.rows.length; weekIndex++){ for (dayInWeek = 0; dayNumber <= daysCount && dayInWeek < this._daysTable.rows[weekIndex].cells.length; dayInWeek ++, dayNumber++){ this._daysTable.rows[weekIndex].cells[dayInWeek].innerHTML = dayNumber; } } //余下行清零 weekIndex --; for (; weekIndex < this._daysTable.rows.length; weekIndex++){ for (; dayInWeek < this._daysTable.rows[weekIndex].cells.length; dayInWeek ++){ this._daysTable.rows[weekIndex].cells[dayInWeek].innerHTML = ''; } dayInWeek = 0; } }, _CreateCalenday: function(year, month) { /// var theDay = this.selectedDay.day; var weekIndex = 1; var dayNumber = 1; var daysCount = this.selectedDay.GetMonthDays(year, month);//月中日数 var dayInWeek = new Date(year, month - 1, 1).getDay();//初始周中日数 //第一行清零 for (var i = 0; i < dayInWeek && i < this._daysTable.rows[weekIndex].cells.length; i++){ this._daysTable.rows[weekIndex].cells[i].innerHTML = ''; } //第一行显示 for (; dayInWeek < this._daysTable.rows[weekIndex].cells.length; dayInWeek++, dayNumber++){ this._daysTable.rows[weekIndex].cells[dayInWeek].innerHTML = dayNumber; if(year == this.selectedDay.year && month == this.selectedDay.month && theDay == dayNumber){ this._OnCurrentDayChanging(this._daysTable.rows[weekIndex].cells[dayInWeek]); } } //内容行显示 for (weekIndex ++;dayNumber <= daysCount && weekIndex < this._daysTable.rows.length; weekIndex++){ for (dayInWeek = 0; dayNumber <= daysCount && dayInWeek < this._daysTable.rows[weekIndex].cells.length; dayInWeek ++, dayNumber++){ this._daysTable.rows[weekIndex].cells[dayInWeek].innerHTML = dayNumber; if(year == this.selectedDay.year && month == this.selectedDay.month && theDay == dayNumber){ this._OnCurrentDayChanging(this._daysTable.rows[weekIndex].cells[dayInWeek]); } } } //余下行清零 weekIndex --; for (; weekIndex < this._daysTable.rows.length; weekIndex++){ for (; dayInWeek < this._daysTable.rows[weekIndex].cells.length; dayInWeek ++){ this._daysTable.rows[weekIndex].cells[dayInWeek].innerHTML = ''; } dayInWeek = 0; } }, _OnYearChanging: function(sender, args){ switch(args){ case "up": var ops = sender.options; var max = parseInt(ops[1].value) - 20; for(var i = 1; i < 21; i ++, max ++){ ops[i].value = max; ops[i].text = max; } sender.selectedIndex = 20; args = ops[20].value; break; case "down": var ops = sender.options; var max = parseInt(ops[1].value) + 20; for(var i = 1; i < 21; i ++, max ++){ ops[i].value = max; ops[i].text = max; } sender.selectedIndex = 1; args = ops[1].value; break; default: break; } this._Refresh(args, this._monthsSelect.value); }, _OnMonthChanging: function(sender, args){ this._Refresh(this._yearsSelect.value, args); }, _OnDayChanging: function(sender, args){ if(args == '') args = 1; this.selectedDay = new CalendarDay(this._yearsSelect.value, this._monthsSelect.selectedIndex + 1, args); this._OnCurrentDayChanging(sender); if(this._SelectedDayChangedEvent != null) this._SelectedDayChangedEvent(sender, this.selectedDay); }, IsVisible: function(){ return this._toolTip.IsVisible(); }, Hidden: function(){ //关闭选择窗口 this._toolTip.Hidden(); }, Show: function(sender, args){ /// /// 发送者. /// 当前日期. if(this._yearsSelect == undefined){//第一次加载. Tooltip 中有对当前控件的缓存, 因此这里没有必要重复计算. this.selectedDay = args; this.offsetTop = sender.offsetTop; this.offsetLeft = sender.offsetLeft; this.clientHeight = sender.clientHeight; this.clientWidth = sender.clientWidth; this._toolTip.Show(sender, this); this._yearsSelect = document.getElementById([this.Id, '_yearsSelect'].join('')); this._monthsSelect = document.getElementById([this.Id, '_monthsSelect'].join('')); this._daysTable = document.getElementById([this.Id, '_daysTable'].join('')); for (var weekIndex = 0, dayInWeek = 0; weekIndex < this._daysTable.rows.length; weekIndex++){ for (; dayInWeek < this._daysTable.rows[weekIndex].cells.length; dayInWeek ++){ cell = this._daysTable.rows[weekIndex].cells[dayInWeek]; switch(dayInWeek){ case 0://星期日 cell.style.color = 'red'; break; case 6://星期六 cell.style.color = 'green'; break; default://其他 break; } } dayInWeek = 0; } this._CreateCalenday(this._yearsSelect.value, this._monthsSelect.value); } else{ this._toolTip.Show(sender, this); } } } function CalendarDay(year, month, day){ /// this._Init(year, month, day); } CalendarDay.prototype = { _daysCountOfMonths: new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), _Init: function(year, month, day){ this.CheckDate(year, month, day); var today = new Date(); this.year = today.getFullYear();//年份. this.month = today.getMonth() + 1;//月份. this.day = today.getDate();//月中日数. if(year == undefined) return; this.year = year; if(month == undefined) return; this.month = month; if(day == undefined) return; this.day = day; this._dayInWeek = -1; }, _GetSubNumber: function(string, head, tail){ if(head == ''){ var t = string.indexOf(tail); if(t < 0) throw {name: "", message:""}; return string.slice(0, t); } else if(tail == ''){ var h = string.lastIndexOf(head) + 1; if(h < 1) throw {name: "", message: ""}; return string.slice(h); } else{ var h = string.indexOf(head) + 1; if(h < 1) throw {name: "", message: ""}; var t = string.indexOf(tail, h); if(t < 0) throw {name: "", message:""}; return string.slice(h, t); } }, CheckDate: function(year, month, day){ /// /// 年份. /// 月份. /// 月中日数. /// if(year == undefined) return; if(year < 0) throw {name:"ArgumentOutOfRangeException", message:"参数越界, 参数名 year."}; if(month == undefined) return; if (month < 1 || month > 12) throw {name:"ArgumentOutOfRangeException", message:"参数越界, 参数名 month."}; if(day == undefined) return; if (day < 1 || day > 31) throw {name:"ArgumentOutOfRangeException", message:"参数越界, 参数名 day."}; if (day == 31 && (month == 4 || month == 6 || month == 9 || month == 11))//检查小月 throw {name:"ArgumentOutOfRangeException", message:"参数越界, 参数名 day."}; if (month == 2 && (day > 29 || (day == 29 && !this.IsLeapYear(year))))//检查闰月 throw {name:"ArgumentOutOfRangeException", message:"参数越界, 参数名 day."}; }, GetDayInWeek: function(){ if(this._dayInWeek < 0){ this._dayInWeek = new Date(this.year, this.month - 1, this.day).getDay(); } return this._dayInWeek; }, IsLeapYear: function(year){ /// /// 年份. /// if(year < 0) throw {name:"ArgumentOutOfRangeException", message:"参数越界, 参数名 year."}; return ((year % 4) == 0) && ((year % 100 != 0)) || (year % 400) == 0; }, GetMonthDays: function(year, month){ /// /// 年份. /// 月份. /// if(year < 0) throw {name:"ArgumentOutOfRangeException", message:"参数越界, 参数名 year."}; if(month < 1 || month > 12) throw {name:"ArgumentOutOfRangeException", message:"参数越界, 参数名 month."}; if (month == 2 && this.IsLeapYear(year))//闰年闰月 return 29; return this._daysCountOfMonths[month - 1]; }, FromText: function(text, yearCaption, monthCaption, dayCaption){ /// /// 日期表达式, 顺序为年、月、日. if(text == undefined || text == null || text == ''){ throw {name:"ArgumentNullException", message:"参数为空, 参数名 text."}; } if(yearCaption == undefined || yearCaption == null || yearCaption == '') yearCaption = '-'; if(monthCaption == undefined || monthCaption == null || monthCaption == '') monthCaption = '-'; if(dayCaption == undefined || dayCaption == null) dayCaption = ''; var year = parseInt(this._GetSubNumber(text, '', yearCaption)); var month = parseInt(this._GetSubNumber(text, yearCaption, monthCaption)); var day = parseInt(this._GetSubNumber(text, monthCaption, dayCaption)); this.CheckDate(year, month, day); this.year = year; this.month = month; this.day = day; this._dayInWeek = -1; }, GetText: function(yearCaption, monthCaption, dayCaption){ /// if(yearCaption == undefined || yearCaption == null || yearCaption == '') yearCaption = '-'; if(monthCaption == undefined || monthCaption == null || monthCaption == '') monthCaption = '-'; if(dayCaption == undefined || dayCaption == null) dayCaption = ''; return [this.year, yearCaption, this.month, monthCaption, this.day, dayCaption].join(''); }, GetLocalMonth: function(calendarMonths){ return calendarMonths.List[this.month - 1]; }, GetLocalWeekDay: function(calendarWeekDays){ return calendarWeekDays.List[this.GetDayInWeek()]; } } function CalendarMonths(names){ /// /// 月自定义名称数组. if(names == undefined){ this.List = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); } else{ if(names.length != 12) throw {name:"ArgumentException", message:"非法参数类型, 参数名 names."}; this.List = names; } } function CalendarWeekDays(names){ /// /// 周中日自定义名称数组. if(names == undefined){ this.List = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); } else{ if(names.length != 7) throw {name:"ArgumentException", message:"非法参数类型, 参数名 names."}; this.List = names; } } ///
下载源码(20080824)
曾经,我发布过《几个Javascript类》,得到部分朋友的支持;有道是,授之予鱼,不如授之予渔。同时结合朋友们的评价,我对该日历控件做了兼容性检查,已经“基本”支持火狐浏览器应用了;遗留一个小问题,火狐下面“日”提取有问题,不知道有兴趣的朋友能不能在读完本文后自己动手修正该漏洞(提示:火狐不支持 element.innerText,但支持 innerHTML :))。
每个人都是从“不会”到“会”(或者,从无到有)走过来的。当初为了这样一个在静态 html 文件可应用的轻量级控件,找了不少站点。源于自己出身于 c#,故在应用方式上做了类 c# 包装。
先谈怎么应用,然后说我是怎么实现的。以下是我在源码包中的演示代码:
- function CalendarDemon(){
-
-
-
-
-
-
-
-
-
- window.myCalendar = null;
- window.currentDay = null;
- window.myTextBox = null;
- window.DayChangedCallback = null;
- window.MyCalendarPerforms = null;
-
-
- DayChangedCallback = function(sender, args){
- try{
- currentDay = args;
- myTextBox.value = currentDay.GetText("年", "月", "日");
-
- }
- catch(e){
- alert(e.message);
- }
- }
-
-
- MyCalendarPerforms = function(textBox){
- try{
- if(myCalendar.IsVisible())
- myCalendar.Hidden();
- else{
- if(myTextBox.value != '')
- currentDay.FromText(myTextBox.value, "年", "月", "日");
- myCalendar.Show(myTextBox, currentDay);
- }
- }
- catch(e){
- alert(e.message);
- }
- }
-
-
- document.write("<div id='calendarPannel' style='position:absolute; z-index:1; dispay:none;'></div>");
- var pannel = document.getElementById('calendarPannel');
-
-
- document.write('<input id="myTextBox" type="text" οnclick="javascript:MyCalendarPerforms(this);" />');
- myTextBox = document.getElementById('myTextBox');
-
-
- var months = new CalendarMonths(["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]);
- var weekdays = new CalendarWeekDays(["日","一","二","三","四","五","六"]);
-
-
- currentDay = new CalendarDay();
-
-
- myCalendar = new Calendar('myCalendar', pannel, DayChangedCallback, 5, -150, currentDay, months, weekdays);
- }
应用它涉及到 5 个关键全局变量的定义。该控件实例,当前所选择的日期实例,显示当前日期的绑定控件,日期选择后的回调函数以及激活日历的方法。月份等显示支持本地化设置,甚至当前日期的输出也支持本地化。
“揭密该控件的实现内幕”:
-
-
- function Calendar(Id, pannel, SelectedDayChangedEvent, toper, lefter, selectedDay, calendarMonths, calendarWeekDays){
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- this._Init(Id, pannel, SelectedDayChangedEvent, toper, lefter, selectedDay, calendarMonths, calendarWeekDays);
- }
-
- Calendar.prototype = {
- _Init: function(Id, pannel, SelectedDayChangedEvent, toper, lefter, selectedDay, calendarMonths, calendarWeekDays){
- },
- _DrawCallback: function(sender, args){
-
- },
- _Render: function(temp){
-
- },
- _RenderYear: function(temp){
-
- },
- _RenderMonth: function(temp){
-
- },
- _RenderWeek: function(temp){
-
- },
- _RenderDay: function(temp){
-
- },
- _OnCurrentDayChanging: function(dayCell){
- },
- _Refresh: function(year, month) {
-
- },
- _CreateCalenday: function(year, month) {
-
- },
- _OnYearChanging: function(sender, args){
- },
- _OnMonthChanging: function(sender, args){
- },
- _OnDayChanging: function(sender, args){
- },
- IsVisible: function(){
- },
- Hidden: function(){
- },
- Show: function(sender, args){
- }
- }
-
- function CalendarDay(year, month, day){
-
- this._Init(year, month, day);
- }
-
- CalendarDay.prototype = {
- _daysCountOfMonths: new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
- _Init: function(year, month, day){
- },
- _GetSubNumber: function(string, head, tail){
- },
- CheckDate: function(year, month, day){
-
-
-
-
-
- },
- GetDayInWeek: function(){
- },
- IsLeapYear: function(year){
-
-
-
- },
- GetMonthDays: function(year, month){
-
-
-
-
- },
- FromText: function(text, yearCaption, monthCaption, dayCaption){
-
-
- },
- GetText: function(yearCaption, monthCaption, dayCaption){
-
- },
- GetLocalMonth: function(calendarMonths){
- },
- GetLocalWeekDay: function(calendarWeekDays){
- }
- }
-
- function CalendarMonths(names){
-
-
- }
-
- function CalendarWeekDays(names){
-
-
- }
如上所示,我将该控件分解为三个类进行实现,Calendar 只负责绘制子控件以及事件收集,CalendarDay 负责对时间进行核准、计算以及输出,剩下两个类似枚举的辅助类。对于 Tooltip,这是我早前包装的,不是为日历控件特制。这些都有别于原始素材(注意类 Calendar 注释中的 see 以及 seealso 部分),感兴趣的朋友可以就可复用性进行对比。
Calendar 只对外透露三个方法: Show(),Hidden(),IsVisible()。何时显示、何时掩藏,都由应用开发者定制,这给开发人员在不同场合的应用制造了便利。
在控件核心类 Calendar 的绘制算法上,我将年(_RenderYear())、月(_RenderMonth())、周(_RenderWeek())、日(_RenderDay())独立为方法进行输出,有利于代码的自说明,更方便朋友们的定制与修正。在后期的更新中,我在“年”下拉框上增加了“更多过去”与“更多将来”下拉选项,使得年份也不会拘泥于某个特定时间段,而扩展到了无限。而在显示控件(Show())时,为了防止大量重复计算,只在初次加载控件时进行绘制;但这造成一个小问题,用户当前输入框中的内容只在初始化会同步到控件,其他时刻,控件将忽略。如下代码:
- Show: function(sender, args){
-
-
-
- if(this._yearsSelect == undefined){
- this.selectedDay = args;
- this.offsetTop = sender.offsetTop;
- this.offsetLeft = sender.offsetLeft;
- this.clientHeight = sender.clientHeight;
- this.clientWidth = sender.clientWidth;
- this._toolTip.Show(sender, this);
- this._yearsSelect = document.getElementById([this.Id, '_yearsSelect'].join(''));
- this._monthsSelect = document.getElementById([this.Id, '_monthsSelect'].join(''));
- this._daysTable = document.getElementById([this.Id, '_daysTable'].join(''));
- for (var weekIndex = 0, dayInWeek = 0; weekIndex < this._daysTable.rows.length; weekIndex++){
- for (; dayInWeek < this._daysTable.rows[weekIndex].cells.length; dayInWeek ++){
- cell = this._daysTable.rows[weekIndex].cells[dayInWeek];
- switch(dayInWeek){
- case 0:
- cell.style.color = 'red';
- break;
- case 6:
- cell.style.color = 'green';
- break;
- default:
- break;
- }
- }
- dayInWeek = 0;
- }
- this._CreateCalenday(this._yearsSelect.value, this._monthsSelect.value);
- }
- else{
- this._toolTip.Show(sender, this);
- }
- }
在日期类 CalendarDay 的设计上,针对日期的输出形式仍有较大开发空间。在后期的更新中,我只是简单的加了对年月日的重命名输出,以及对该输出的反向识别,但没有实现类 c# 的 ToString("yyMMdd") 等方法。看我的具体实现:
- FromText: function(text, yearCaption, monthCaption, dayCaption){
-
-
- if(text == undefined || text == null || text == ''){
- throw {name:"ArgumentNullException", message:"参数为空, 参数名 text."};
- }
- if(yearCaption == undefined || yearCaption == null || yearCaption == '')
- yearCaption = '-';
- if(monthCaption == undefined || monthCaption == null || monthCaption == '')
- monthCaption = '-';
- if(dayCaption == undefined || dayCaption == null)
- dayCaption = '';
- var year = parseInt(this._GetSubNumber(text, '', yearCaption));
- var month = parseInt(this._GetSubNumber(text, yearCaption, monthCaption));
- var day = parseInt(this._GetSubNumber(text, monthCaption, dayCaption));
- this.CheckDate(year, month, day);
- this.year = year;
- this.month = month;
- this.day = day;
- this._dayInWeek = -1;
- },
- GetText: function(yearCaption, monthCaption, dayCaption){
-
- if(yearCaption == undefined || yearCaption == null || yearCaption == '')
- yearCaption = '-';
- if(monthCaption == undefined || monthCaption == null || monthCaption == '')
- monthCaption = '-';
- if(dayCaption == undefined || dayCaption == null)
- dayCaption = '';
- return [this.year, yearCaption, this.month, monthCaption, this.day, dayCaption].join('');
- },
开发过程的乐趣在于,你所做的给自己或者别人带来了一些便利;对于学习开发的入门兄弟来说更是如此。总是说程序员大概都是懒人,能复用的代码,绝不写第二遍;有些人甚至因此偏执于搞复用:用最少的现有代码,延用过去做好的“控件”。但能否在各种场景下复用,就看你对经验的总结了。
虽然都是小把戏,但还是善意的提醒朋友们:将一个计算过程分滩给多个方法,每个方法短而功能明确,这对以后追加功能或是查找漏洞都会很有帮助。什么时候,我能把设计模式给搞透?