欢迎加入QQ讨论群258996829
麦子学院 头像
苹果6袋
6
麦子学院

bootstrap时间选择器实现源码分享

发布时间:2016-10-03 21:34  回复:0  查看:3002   最后回复:2016-10-03 21:34  

bootstrap框架中的时间选择器有两种: dateTimePicke r和 dateRangePicker,今天就和大家一起来扒一扒其具体用法和实现源码。

 

1、dateTimePicker好像是官方嫡插件:

 

需要的文件:

 

1 <link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css">

2 <script src="js/bootstrap-datetimepicker.min.js"></script>

3 <script src="js/bootstrap-datetimepicker.zh-CN.js"></script>

4 <script src="js/moment.min.js"></script>

API直接参考:http://www.bootcss.com/p/bootstrap-datetimepicker/

 

2、dateRangePicker好像是第三方插件,它最终的是可以实现时间段的选择:

 

效果

 

需要的文件:

 

1 <link rel="stylesheet" href="css/daterangepicker-bs3.css">

2 <script src="js/daterangepicker.js"></script>

3 <script src="js/moment.min.js"></script>

 html代码:

 

 1 <div>

 2     <div style="margin-top:5px">

 3         <div>

 4             <div>

 5                 <label>

 6                     日期:

 7                 </label>

 8                 <div>

 9                     <div id="reportrange" class="pull-left dateRange" style="width:350px">

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

11                         <span id="searchDateRange"></span>

12                         <b></b>

13                     </div>

14                 </div>

15             </div>

16         </div>

17     </div>

18 </div>

js代码:

 

 1 <script type="text/javascript">

 2     $(document).ready(function (){

 3         //时间插件

 4         $('#reportrange span').html(moment().subtract('hours', 1).format('YYYY-MM-DD HH:mm:ss') + ' - ' + moment().format('YYYY-MM-DD HH:mm:ss'));

 5         $('#reportrange').daterangepicker(

 6                 {

 7                     // startDate: moment().startOf('day'),

 8                     //endDate: moment(),

 9                     //minDate: '01/01/2012',    //最小时间

10                     maxDate : moment(), //最大时间

11                     dateLimit : {

12                         days : 30

13                     }, //起止时间的最大间隔

14                     showDropdowns : true,

15                     showWeekNumbers : false, //是否显示第几周

16                     timePicker : true, //是否显示小时和分钟

17                     timePickerIncrement : 60, //时间的增量,单位为分钟

18                     timePicker12Hour : false, //是否使用12小时制来显示时间

19                     ranges : {

20                         //'最近1小时': [moment().subtract('hours',1), moment()],

21                         '今日': [moment().startOf('day'), moment()],

22                         '昨日': [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],

23                         '最近7': [moment().subtract('days', 6), moment()],

24                         '最近30': [moment().subtract('days', 29), moment()]

25                     },

26                     opens : 'right', //日期选择框的弹出位置

27                     buttonClasses : [ 'btn btn-default' ],

28                     applyClass : 'btn-small btn-primary blue',

29                     cancelClass : 'btn-small',

30                     format : 'YYYY-MM-DD HH:mm:ss', //控件中fromto 显示的日期格式

31                     separator : ' to ',

32                     locale : {

33                         applyLabel : '确定',

34                         cancelLabel : '取消',

35                         fromLabel : '起始时间',

36                         toLabel : '结束时间',

37                         customRangeLabel : '自定义',

38                         daysOfWeek : [ '日', '', '', '', '', '', '' ],

39                         monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月',

40                             '七月', '八月', '九月', '十月', '十一月', '十二月' ],

41                         firstDay : 1

42                     }

43                 }, function(start, end, label) {//格式化日期显示框

44                     $('#reportrange span').html(start.format('YYYY-MM-DD HH:mm:ss') + ' - ' + end.format('YYYY-MM-DD HH:mm:ss'));

45                 });

46         //设置日期菜单被选项  --开始--

47         /*

48          var dateOption ;

49          if("${riqi}"=='day') {

50          dateOption = "今日";

51          }else if("${riqi}"=='yday') {

52          dateOption = "昨日";

53          }else if("${riqi}"=='week'){

54          dateOption ="最近7";

55          }else if("${riqi}"=='month'){

56          dateOption ="最近30";

57          }else if("${riqi}"=='year'){

58          dateOption ="最近一年";

59          }else{

60          dateOption = "自定义";

61          }

62          $(".daterangepicker").find("li").each(function (){

63          if($(this).hasClass("active")){

64          $(this).removeClass("active");

65          }

66          if(dateOption==$(this).html()){

67          $(this).addClass("active");

68          }

69          });*/

70         //设置日期菜单被选项  --结束--

71     })

72 </script>

但是这里的月份汉化存在问题,建议需要去 moment.min.js 文件里面去修改

 

也可以在后期汉化,比较完整的代码:

 

  1 var table;

  2    $(function () {

  3        table = $('#example').DataTable({

  4            "ajax": {

  5                "url":"/example/resources/server_processing_customCUrl.php",

  6                "data": function ( d ) {

  7                    //添加额外的参数传给服务器

  8                    d.extra_search = $('#reportrange span').html();

  9                }},

 10            "processing": true,

 11            "serverSide": true,

 12            "language": {

 13                "sProcessing": "处理中...",

 14                "sLengthMenu": "显示 _MENU_ 项结果",

 15                "sZeroRecords": "没有匹配结果",

 16                "sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ ",

 17                "sInfoEmpty": "显示第 至 项结果,共 ",

 18                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",

 19                "sInfoPostFix": "",

 20                "sSearch": "搜索:",

 21                "sUrl": "",

 22                "sEmptyTable": "表中数据为空",

 23                "sLoadingRecords": "载入中...",

 24                "sInfoThousands": ",",

 25                "oPaginate": {

 26                    "sFirst": "首页",

 27                    "sPrevious": "上页",

 28                    "sNext": "下页",

 29                    "sLast": "末页"

 30                },

 31                "oAria": {

 32                    "sSortAscending": ": 以升序排列此列",

 33                    "sSortDescending": ": 以降序排列此列"

 34                }

 35            },

 36            "dom":

 37                    "<'row'<'span9'l<'#mytoolbox'>><'span3'f>r>"+

 38                    "t"+

 39                    "<'row'<'span6'i><'span6'p>>"  ,

 40            initComplete:initComplete

 41        });

 42  

 43    });

 44  

 45    /**

 46     * 表格加载渲染完毕后执行的方法

 47     * @param data

 48     */

 49    function initComplete(data){

 50  

 51        var dataPlugin =

 52                '<div id="reportrange" class="pull-left dateRange" style="width:400px;margin-left: 10px"> '+

 53                '日期:<i class="glyphicon glyphicon-calendar fa fa-calendar"></i> '+

 54                '<span id="searchDateRange"></span>  '+

 55                '<b></b></div> ';

 56        $('#mytoolbox').append(dataPlugin);

 57        //时间插件

 58        $('#reportrange span').html(moment().subtract('hours', 1).format('YYYY-MM-DD HH:mm:ss') + ' - ' + moment().format('YYYY-MM-DD HH:mm:ss'));

 59  

 60        $('#reportrange').daterangepicker(

 61                {

 62                    // startDate: moment().startOf('day'),

 63                    //endDate: moment(),

 64                    //minDate: '01/01/2012',    //最小时间

 65                    maxDate : moment(), //最大时间

 66                    dateLimit : {

 67                        days : 30

 68                    }, //起止时间的最大间隔

 69                    showDropdowns : true,

 70                    showWeekNumbers : false, //是否显示第几周

 71                    timePicker : true, //是否显示小时和分钟

 72                    timePickerIncrement : 60, //时间的增量,单位为分钟

 73                    timePicker12Hour : false, //是否使用12小时制来显示时间

 74                    ranges : {

 75                        //'最近1小时': [moment().subtract('hours',1), moment()],

 76                        '今日': [moment().startOf('day'), moment()],

 77                        '昨日': [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],

 78                        '最近7': [moment().subtract('days', 6), moment()],

 79                        '最近30': [moment().subtract('days', 29), moment()]

 80                    },

 81                    opens : 'right', //日期选择框的弹出位置

 82                    buttonClasses : [ 'btn btn-default' ],

 83                    applyClass : 'btn-small btn-primary blue',

 84                    cancelClass : 'btn-small',

 85                    format : 'YYYY-MM-DD HH:mm:ss', //控件中fromto 显示的日期格式

 86                    separator : ' to ',

 87                    locale : {

 88                        applyLabel : '确定',

 89                        cancelLabel : '取消',

 90                        fromLabel : '起始时间',

 91                        toLabel : '结束时间',

 92                        customRangeLabel : '自定义',

 93                        daysOfWeek : [ '日', '', '', '', '', '', '' ],

 94                        monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月',

 95                            '七月', '八月', '九月', '十月', '十一月', '十二月' ],

 96                        firstDay : 1

 97                    }

 98                }, function(start, end, label) {//格式化日期显示框

 99  

100                    $('#reportrange span').html(start.format('YYYY-MM-DD HH:mm:ss') + ' - ' + end.format('YYYY-MM-DD HH:mm:ss'));

101                });

102  

103        //设置日期菜单被选项  --开始--

104        var dateOption ;

105        if("${riqi}"=='day') {

106            dateOption = "今日";

107        }else if("${riqi}"=='yday') {

108            dateOption = "昨日";

109        }else if("${riqi}"=='week'){

110            dateOption ="最近7";

111        }else if("${riqi}"=='month'){

112            dateOption ="最近30";

113        }else if("${riqi}"=='year'){

114            dateOption ="最近一年";

115        }else{

116            dateOption = "自定义";

117        }

118        $(".daterangepicker").find("li").each(function (){

119            if($(this).hasClass("active")){

120                $(this).removeClass("active");

121            }

122            if(dateOption==$(this).html()){

123                $(this).addClass("active");

124            }

125        });

126        //设置日期菜单被选项  --结束--

127  

128  

129        //选择时间后触发重新加载的方法

130        $("#reportrange").on('apply.daterangepicker',function(){

131            //当选择时间后,出发dt的重新加载数据的方法

132            table.ajax.reload();

133            //获取dt请求参数

134            var args = table.ajax.params();

135            console.log("额外传到后台的参数值extra_search为:"+args.extra_search);

136        });

137  

138        function getParam(url) {

139            var data = decodeURI(url).split("?")[1];

140            var param = {};

141            var strs = data.split("&");

142  

143            for(var i = 0; i<strs.length; i++){

144                param[strs[i].split("=")[0]] = strs[i].split("=")[1];

145            }

146            return param;

147        }

148    }

 

 

 

文章来源:博客园

您还未登录,请先登录

热门帖子

最新帖子