asp.net日历控件开发(1)

本文介绍了一款基于jQuery的自定义日历控件,该控件支持多种日期格式,并提供了日视图、月视图及年视图等功能。作者因未找到满意的现成日历控件,故自行开发了这款轻量级且易于定制的日历插件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    现在网站上有很多日历控件,有弹出窗口形式的,纯js脚本的,有基于Extjs,jQuery版本的,但是却比较符合外国人的习惯,
还有例如My97DatePicker日历控件,功能虽然强大,但是就一个日历控件却搞这么多文件,还不允许打散其文件结构,麻烦。
还有Microsoft提供的AjaxControlToolkit,但是为了一个日历控件引用这个库,确实感到很不爽。非本人愿意重复造轮子,
确实没看到有一个让自己觉得比较爽的日历控件。于是自己js写了个日历,本人提供所有源码下载,不过本人不擅长于界面方面,
如果你在我的基础上调整得比较好看或者修改了一些bug,或者你有更好的,希望你能发我一个,不胜感激。
在接下来我准备将其封装成asp.net控件,以后拖放就更方便了。
日历样式:

ContractedBlock.gifExpandedBlockStart.gifCode
  <style type="text/css">
    .monthspan
{width:45px;border:1px solid #0099CC;height:30px;font-size:12px;padding:5px 0px 0px 5px;}
    .yearspan
{width:45px;border:1px solid #0099CC;height:30px;font-size:12px;padding:5px 0px 0px 5px;}
    .dayspan
{width:25px;border:1px solid #0099CC;height:18px;font-size:12px;padding:2px 0px 0px 3px;}
    .notthismonth
{color:#cccccc;}
    .weektag
{font-size:12px;height:20px;}
    .yeartitle
{font-size:13px;font-weight:bold;width:120px;text-align:center;cursor:pointer;}
    .todayspan 
{font-size:12px;color:Red;font-weight:bold;width:180px;}
    .selected 
{color:Red;}
    .prevTag
{font-family:Webdings;cursor:hand;font-size:14px;}
    .nextTag
{font-family:Webdings;cursor:hand;font-size:14px;}
    .prevTagEx
{font-family:Webdings;cursor:hand;font-size:14px;}
    .nextTagEx
{font-family:Webdings;cursor:hand;font-size:14px;}
    .calendarheader 
{background-color:#FFCC00;}
  
</style>
js脚本:
ContractedBlock.gifExpandedBlockStart.gifCode
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
      
var WeekZH = [''''''''''''''];
      
var MonthZH = ['一月''二月''三月''四月''五月''六月''七月''八月''九月''十月''十一月''十二月'];
      
var CalendarGlobalView = null;

      
function Calendar(input, link, format, year, month, day, mindate, maxdate) 
      {
            
var date = new Date();

            
this.Year = year==null||typeof(year) == "undefined" ? date.getFullYear() : year;
            
this.Month = month == null || typeof (month) == "undefined" ? date.getMonth() : month;
            
this.Day = day == null || typeof (day) == "undefined" ? date.getDate() : day;
            
this.Format = format == null || typeof (format) == "undefined" ? "yyyy-MM-dd" : format;
            
this.Mindate = mindate == null || typeof (mindate) == "undefined" ? new Date("1900""01""01") : new Date(mindate.split('-')[0], mindate.split('-')[1], mindate.split('-')[2]);
            
this.Maxdate = maxdate == null || typeof (maxdate) == "undefined" ? new Date("9999""01""01") : new Date(maxdate.split('-')[0], maxdate.split('-')[1], maxdate.split('-')[2]);
            
this.Date = new Date(this.Year,this.Month,this.Day);
            
this.DateStr=this.Year+"-"+this.Month+"-"+this.Day;
            
this.Week = WeekZH[this.Date.getDay()];
            
this._currentView = null;
            
this._monthView = null;
            
this._yearView = null;
            
this._dayView = null;
            
this._inputCtrl = document.getElementById(input);
            
this._linkCtrl = document.getElementById(link); //null;
      }

      Calendar.prototype 
=
    {
        initialize: 
function() {
            
var context = this;
            $(document).bind(
"click"function() {
                
if (context._currentView != null)
                    context.hide();
            })
        },

        show: 
function() {
            
if (this.Format == "yyyy-MM-dd") { this.showDayView(this.DateStr); }
            
if (this.Format == "yyyy/MM/dd") { this.showDayView(this.DateStr); }
            
if (this.Format == "yyyyMMdd") { this.showDayView(this.DateStr); }
            
if (this.Format == "yyyy-MM") { this.showMonthView(this.Year + "-" + this.Month); }
            
if (this.Format == "yyyy/MM") { this.showMonthView(this.Year + "-" + this.Month); }
            
if (this.Format == "yyyyMM") { this.showMonthView(this.Year + "-" + this.Month); }
            
if (this.Format == "yyyy") { this.showYearView(this.Year); }
        },
        hide: 
function() { this._currentView.parentNode.removeChild(this._currentView) },

        getPosition: 
function(obj) {
            
var left = obj.offsetLeft;
            
var top = obj.offsetTop;
            
var parent = obj.parentNode;
            
while (parent.tagName != 'BODY') {
                
if (parent.style.position == "absolute") {
                    parent 
= parent.offsetParent;
                    
continue;
                }
                
if (parent.tagName == "DIV") {
                    top 
= top - parent.scrollTop;
                    left 
= left - parent.scrollLeft;
                }
                left 
+= parent.offsetLeft;
                top 
+= parent.offsetTop;
                parent 
= parent.parentNode;
            }

            
//return { x: left + obj.offsetWidth, y: top + obj.offsetHeight };
            return { x: left, y: top + obj.offsetHeight };
        },

        formatDate: 
function(date, fmt) {
            
var year = date.getFullYear();
            
var month = date.getMonth();
            
var day = date.getDate();
            
var datestr = year + "-" + (month + 1+ "-" + day;
            
if (fmt == 'yyyyMMdd')
                
return datestr.replace(/-/g, '');
            
else if (fmt == 'yyyy/MM/dd')
                
return datestr.replace(/-/g, '/');
            
else
                
return datestr;
        },
        daydiff: 
function(date1, date2) {
            
var timediff = date1.getTime() - date2.getTime();
            
var daysdiff = Math.floor(timediff / (24 * 60 * 60 * 1000));
            
return daysdiff;
        },
        showDayView: 
function(val) {
            
if (CalendarGlobalView != null) CalendarGlobalView.parentNode.removeChild(CalendarGlobalView);
            
var year = new Number(val.split('-')[0]);
            
var month = new Number(val.split('-')[1]);
            
var day = new Number(val.split('-')[2]);
            
var date = new Date(year + "/" + month + "/" + "1");
            
var inputdate = new Date(year + "/" + month + "/" + day);
            
var week = date.getDay();
            
this.datediff(date, -1 * week);
            
var DayZH = [];
            
for (var i = 0; i < 42; i++) {
                DayZH.push(
new Date(date.getFullYear() + "/" + (date.getMonth() + 1+ "/" + date.getDate()));
                
this.datediff(date, 1)
            }

            
var html = "";
            
var dayView = this._createView();
            html 
= "<table border='0' style='width:100%;' cellpadding='0' cellspacing='1'><tr><td colspan='7' class='calendarheader'><span class='prevTagEx'>7</span><span class='prevTag'>3</span><span class='yeartitle'>" + year + "" + month + "月</span><span class='nextTag'>4</span><span class='nextTagEx'>8</span></td></tr>";
            html 
+= "<tr>";
            
for (var i = 0; i < 7; i++) {
                html 
+= "<td class='weektag'>" + WeekZH[i] + "</td>";
            }
            html 
+= "</tr>";
            
for (var j = 0; j < 6; j++) {
                html 
+= "<tr>";
                
for (var i = 0; i < 7; i++) {
                    
var c = j * 7 + i;
                    
if (this.daydiff(inputdate, DayZH[c]) == 0) {
                        html 
+= "<td style='height:20px;'><span class='dayspan selected' val='" + this.formatDate(DayZH[c]) + "'>" + DayZH[c].getDate() + "</span></td>";
                    }
                    
else {
                        
if (DayZH[c].getMonth() != inputdate.getMonth())
                            html 
+= "<td style='height:20px;'><span class='dayspan notthismonth' val='" + this.formatDate(DayZH[c]) + "'>" + DayZH[c].getDate() + "</span></td>";
                        
else
                            html 
+= "<td style='height:20px;'><span class='dayspan' val='" + this.formatDate(DayZH[c]) + "'>" + DayZH[c].getDate() + "</span></td>";
                    }
                }
                html 
+= "</tr>";
            }
            html 
+= "<tr><td colspan='7' style='height:20px;'><span class='todayspan'>今天是:" + new Date().toLocaleDateString() + "</span></td></tr>";
            html 
+= "</table>";
            dayView.innerHTML 
= html;

            
this._currentView = dayView;
            CalendarGlobalView 
= this._currentView;
            
var context = this;
            
//绑定日单击事件
            $(dayView).find('.dayspan').each(function() {
                $(
this).bind("click"function() {
                    
var year = $(this).attr('val').split('-')[0];
                    
var month = $(this).attr('val').split('-')[1];
                    
var day = $(this).attr('val').split('-')[2];
                    context._inputCtrl.value 
= context.formatDate(new Date(year, month - 1, day), context.Format);
                    context.hide();
                });
                $(
this).bind("mouseover"function() { $(this).attr("style""cursor:hand;background-color:#8F96E4"); })
                $(
this).bind("mouseout"function() { $(this).attr("style"""); })
            });

            $(dayView).find(
'.prevTag').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    month 
= month - 1;
                    year 
= new Number(year);
                    
if (month < 0) {
                        year 
= year - 1;
                        month 
= 12;
                    }
                    context.showDayView(year 
+ "-" + month + "-" + day);
                });
            });
            $(dayView).find(
'.nextTag').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    month 
= month + 1;
                    year 
= new Number(year);
                    
if (month > 12) {
                        year 
= year + 1;
                        month 
= 1;
                    }
                    context.showDayView(year 
+ "-" + month + "-" + day);
                });
            });
            $(dayView).find(
'.prevTagEx').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    year 
= new Number(year) - 1;
                    context.showDayView(year 
+ "-" + month + "-" + day);
                });
            });
            $(dayView).find(
'.nextTagEx').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    year 
= new Number(year) + 1;
                    context.showDayView(year 
+ "-" + month + "-" + day);
                });
            });
            $(dayView).find(
'.yeartitle').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    context.showYearView(year, 
true);
                });
            });
        },

        datediff: 
function(date, days) {
            date 
= date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
        },

        _createView: 
function() {
            
var el = this._linkCtrl;
            
var view = document.createElement("DIV");
            
var pos = this.getPosition(el);
            view.style.backgroundColor 
= "lightyellow";
            view.style.border 
= "solid #5F5F5F 1px";
            view.style.left 
= pos.x + "px";
            view.style.top 
= pos.y + "px";
            view.style.width 
= "180px";
            view.style.height 
= "180px";
            view.style.position 
= "absolute";
            view.style.zIndex 
= "1000";
            el.parentNode.appendChild(view);
            
return view;
        },

        showMonthView: 
function(val, ifgo) {
            
if (CalendarGlobalView != null) CalendarGlobalView.parentNode.removeChild(CalendarGlobalView);
            
var year = val.split('-')[0];
            
var month = val.split('-')[1];
            month 
= new Number(month);
            
var html = "";
            
var monthView = this._createView();
            html 
= "<table border='0' cellpadding='0' cellspacing='1'><tr><td colspan='4' class='calendarheader'><span class='prevTagEx'>7</span><span class='prevTag'>3</span><span class='yeartitle'>" + year + "" + month + "月</span><span class='nextTag'>4</span><span class='nextTagEx'>8</span></td></tr>";
            
for (var j = 0; j < 3; j++) {
                html 
+= "<tr>";
                
for (var i = 0; i < 4; i++) {
                    
var c = j * 4 + i;
                    
if ((c + 1== month)
                        html 
+= "<td style='height:20px;'><span class='monthspan selected' val='" + (c + 1+ "'>" + MonthZH[c] + "</span></td>";
                    
else
                        html 
+= "<td style='height:20px;'><span class='monthspan' val='" + (c + 1+ "'>" + MonthZH[c] + "</span></td>";
                }
                html 
+= "</tr>";
            }
            html 
+= "<tr><td colspan='4' style='height:20px;'><span class='todayspan'>今天是:" + new Date().toLocaleDateString() + "</span></td></tr>";
            html 
+= "</table>";
            monthView.innerHTML 
= html;
            
this._currentView = monthView;
            CalendarGlobalView 
= this._currentView;
            
var context = this;
            
//绑定月单击事件
            $(monthView).find('.monthspan').each(function() {
            $(
this).bind("click"function() {
                    
if (ifgo && context.Format.indexOf('dd')>0) {
                        context.hide();
                        context.showDayView(year 
+ "-" + $(this).attr('val'+ "-1");
                    }
                    
else {
                        
if (context.Format == 'yyyy/MM')
                            context._inputCtrl.value 
= year + "/" + $(this).attr('val');
                        
else if (context.Format == 'yyyyMM')
                            context._inputCtrl.value 
= year + $(this).attr('val');
                        
else
                            context._inputCtrl.value 
= year + "-" + $(this).attr('val');

                        context.hide();
                    }
                });
                $(
this).bind("mouseover"function() { $(this).attr("style""cursor:hand;background-color:#8F96E4"); })
                $(
this).bind("mouseout"function() { $(this).attr("style"""); })
            });
            $(monthView).find(
'.prevTag').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    month 
= month - 1;
                    year 
= new Number(year);
                    
if (month < 0) {
                        year 
= year - 1;
                        month 
= 12;
                    }
                    context.showMonthView(year 
+ "-" + month);
                });
            });
            $(monthView).find(
'.nextTag').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    month 
= month + 1;
                    year 
= new Number(year);
                    
if (month > 12) {
                        year 
= year + 1;
                        month 
= 1;
                    }
                    context.showMonthView(year 
+ "-" + month);
                });
            });
            $(monthView).find(
'.prevTagEx').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    year 
= new Number(year) - 1;
                    context.showMonthView(year 
+ "-" + month);
                });
            });
            $(monthView).find(
'.nextTagEx').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    year 
= new Number(year) + 1;
                    context.showMonthView(year 
+ "-" + month);
                });
            });
            $(monthView).find(
'.yeartitle').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    context.showYearView(year, 
true);
                });
            });
        },

        showYearView: 
function(val, ifgo) {
            
if (CalendarGlobalView != null) CalendarGlobalView.parentNode.removeChild(CalendarGlobalView);
            
var yearView = this._createView();
            
var year = val;
            
if (isNaN(parseInt(val))) year = new Date().getFullYear();
            
var minYear = new Number(year) - 6;
            
var maxYear = new Number(year) + 5;
            
var yearArr = [];
            
for (var i = 0; i < 12; i++)
                yearArr.push(minYear 
+ i);
            
var html = "";
            html 
= "<table border='0' cellpadding='0' cellspacing='1'><tr><td colspan='4' class='calendarheader'><span class='prevTagEx'>7</span><span class='prevTag'>3</span><span class='yeartitle'>" + minYear + "" + maxYear + "</span><span class='nextTag'>4</span><span class='nextTagEx'>8</span></td></tr>"
            
for (var j = 0; j < 3; j++) {
                html 
+= "<tr>";
                
for (var i = 0; i < 4; i++) {
                    
var c = j * 4 + i;
                    
if (yearArr[c] == new Number(year))
                        html 
+= "<td style='height:20px;'><span class='yearspan selected' val='" + yearArr[c] + "'>" + yearArr[c] + "</span></td>";
                    
else
                        html 
+= "<td style='height:20px;'><span class='yearspan' val='" + yearArr[c] + "'>" + yearArr[c] + "</span></td>";
                }
                html 
+= "</tr>";
            }
            html 
+= "<tr><td colspan='4' style='height:20px;'><span class='todayspan'>今天是:" + new Date().toLocaleDateString() + "</span></td></tr>";
            html 
+= "</table>";
            yearView.innerHTML 
= html;
            
this._currentView = yearView;
            CalendarGlobalView 
= this._currentView;
            
var context = this;
            
//绑定年单击事件
            $(yearView).find('.yearspan').each(function() {
                $(
this).bind("click"function() {
                    
if (ifgo) {
                        context.hide();
                        context.showMonthView($(
this).attr('val'+ "-1", ifgo);
                    }
                    
else {
                        context._inputCtrl.value 
= $(this).attr('val');
                        context.hide();
                    }
                });
                $(
this).bind("mouseover"function() { $(this).attr("style""cursor:hand;background-color:#8F96E4"); })
                $(
this).bind("mouseout"function() { $(this).attr("style"""); })
            });
            $(yearView).find(
'.prevTag').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    context.showYearView(
new Number(year) - 1);
                });
            });
            $(yearView).find(
'.nextTag').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    context.showYearView(
new Number(year) + 1);
                });
            });
            $(yearView).find(
'.prevTagEx').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    context.showYearView(
new Number(year) - 10);
                });
            });
            $(yearView).find(
'.nextTagEx').each(function() {
                $(
this).bind("click"function() {
                    context.hide();
                    context.showYearView(
new Number(year) + 10);
                });
            });
        }
    }

  
</script>
页面测试和调用
ContractedBlock.gifExpandedBlockStart.gifCode
<script type="text/javascript">
    
var cal = new Calendar('txt','txt','yyyy-MM-dd');
    cal.show();
</script>
<div style="width:200px;height:200px;border:1px solid #f00;over-flow:auto">
    
<input type="text" id="txt" />
    <div style="width:600px;height:600px;border:1px solid #000;margin:60 80 90 90;padding:60 80 90 90;" id="divp">
    
<input type="button" onmousedown="ButtonClick()" value="测试" id='btn'/>
    </div>
 </div>
日历的三种视图:

转载于:https://www.cnblogs.com/jackhuclan/archive/2009/08/06/1540554.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值