天天看點

bootstrap-daterangepicker:最好用的日期範圍選擇元件

嗯,在我還沒有發現bootstrap-daterangepicker元件時,

在頁面需要選擇日期範圍時,我是傻乎乎的建立兩個日期元件。

現在想想,以前的low勁真是不可忍呐!

零、效果展示

現在是這樣的:

bootstrap-daterangepicker:最好用的日期範圍選擇元件
以前是這樣的:
bootstrap-daterangepicker:最好用的日期範圍選擇元件

不比不知道,一比高下立斷。

一、源碼下載下傳

Date Range Picker for Bootstrap

注意要依賴Bootstrap, jQuery and Moment.js。

Date Range Picker relies on Bootstrap, jQuery and Moment.js. Include the required scripts and stylesheet in your page.

二、使用方法

<div class="form-group daterange">

   <label>下單時間:</label>

   <input class="form-control" name="range_date" type="text">

   <i class="fa fa-calendar"></i>

</div>

外層div上增加daterange class。

一個普通的input标簽。

一個月曆的i标簽。

如此就好。

三、内部封裝

首先是js。

$(function() {
    $(".daterange input").each(function() {
        var $this = $(this);
        $this.daterangepicker({
            locale : {
                "format" : "YYYY-MM-DD",// 顯示格式
                "separator" : " / ",// 兩個日期之間的分割線
                // 中文化
                "applyLabel" : "确定",
                "cancelLabel" : "取消",
                "fromLabel" : "開始",
                "toLabel" : "結束",
                "daysOfWeek" : [ "日", "一", "二", "三", "四", "五", "六" ],
                "monthNames" : [ "一月", "二月", "三月", "四月", "五月", "六", "七月", "八月", "九月", "十月", "十一月", "十二月" ],
                "firstDay" : 1
            },
        }, function(start, end, label) {
            // 點選确定後的事件,下面是為了bootstrap validate得校驗,
            // 若未使用,可忽視
            if ($this.parents("form.required-validate").length > 0) {
                var $form = $this.parents("form.required-validate");
                var name = $this.attr("name");
                if ($form.length > 0) {
                    var data = $form.data('bootstrapValidator');
                    data.updateStatus(name, 'NOT_VALIDATED', null)
                    // Validate the field
                    .validateField(name);
                }
            }
        // 設定最小寬度,否則顯示不全
        }).css("min-width", "210px").next("i").click(function() {
            // 對日期的i标簽增加click事件,使其在滑鼠點選時可以拉出日期選擇
            $(this).parent().find('input').click();
        });
    });
});      

再來看css。

/* 定位i标簽在input标簽内 */
.daterange i {
    position: absolute;
    bottom: 10px;
    right: 14px;
    top: auto;
    cursor: pointer;
}
.daterange {
    position: relative;
}
/* daterange i end */      

繼續閱讀