首页 > 技术文章 > Jquery简单实现Datepicker

sxhNicole 2015-06-17 14:30 原文

cshtml:

<input type="text" id="purchaseDate" name="PurchaseDate" value="<%=order.PurchaseDate !=DateTime.MinValue?order.PurchaseDate.ToLongDateString():DateTime.Now.ToLongDateString()%>" /></label>
         

Jquery:

  //初始化DatePicker
        $.fn.calendar = function () {
            var that = this, as = $('<div id="calnedar"><b>&lt;</b><b style="width:180px"></b><b>&gt;</b><b>日</b><b>一</b><b>二</b><b>三</b><b>四</b><b>五</b><b>六</b><i></i></div>').insertAfter(that), date = new Date();
            as.children().eq(0).on('click', function () {
                date = new Date(date.getFullYear(), date.getMonth() - 1, 1);
                as.range(date);
            }).next().next().on('click', function () {
                date = new Date(date.getFullYear(), date.getMonth() + 1, 1);
                as.range(date);
            });
            for (var i = 1; i < 32; i++) {
                $('<a>' + i + '</a>').appendTo(as).click(function () {
                    that.val(as.css('display', 'none').children().eq(1).html() + this.innerHTML + '日');
                });
            }
            as.children().eq(date.getDate() + 10).attr('class', 'hover');
            as.range(date);   
            return this.mousedown(function () {
                as.css('display', 'block');
            });
        }
        $.fn.range = function (date) {
            var children = this.children(), i = 39;
            children.eq(1).html(date.getFullYear() + '年' + (date.getMonth() + 1) + '月');
            children.eq(10).width(30 * new Date(date.getFullYear(), date.getMonth(), 1).getDay());
            for (; i < new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate() + 11; i++) {
                children.eq(i).css('display', 'block');
            }
            for (; i < 42; i++) {
                children.eq(i).css('display', 'none');
            }
        }
        //将购买时间input实现为datepicker
        $('#purchaseDate').calendar();

 

css:

       #calnedar {
           background-color: #fff;
           border: 1px solid #ddd;
               display: none;
           margin-left: 120px;
           overflow: hidden;
           position: absolute;
           width: 252px;
        }

    #calnedar a, #calnedar b, #calnedar i {
        float: left;
        padding: 5px 0px;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }

    #calnedar a {
        color: #333;
        padding: 5px 6px;
        text-align: right;
        width: 24px;
    }

    #calnedar b {
        background-color: #eee;
        text-align: center;
        width: 36px;
    }

    #calnedar a:hover, #calnedar a.hover {
        background-color: #eee;
    }

 

推荐阅读