前言
利用BootstrapDatepicker添加一个日期选择器
准备工作
引入依赖
1 2 3 4 5 6 7 8 9 10
| <link rel="stylesheet" href="dist/css/bootstrap.css"> <link rel="stylesheet" href="dist/css/bootstrap-datepicker.css"> <link rel="stylesheet" href="dist/css/bootstrap-datepicker.standalone.css">
<script src="dist/js/jquery.js"></script>
<script src="dist/js/bootstrap.js"></script> <script src="dist/js/bootstrap.bundle.js"></script> <script src="dist/js/bootstrap-datepicker.js"></script> <script src="dist/js/bootstrap-datepicker.zh-CN.min.js"></script>
|
HTML生成日期选择器
data-date-format="yyyy-mm-dd hh:ii"
:直接指定日期格式化
value="2012-12-12 12:12"
:指定默认值
1
| <input type="text" id="time">
|
JS初始化日期选择器
1
| $('#time').datepicker();
|
初始化时添加默认配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| $('#time').datepicker({ language: 'zh-CN', autoclose: true, clearBtn: true, format: "yyyy-mm-dd", startDate: "", endDate: "" });
|
内置函数
销毁日期选择器
1 2 3
| $('#time').datepicker('destroy');
$('#time').datepicker('remove');
|
显示日期选择器
1
| $('#time').datepicker('show');
|
隐藏日期选择器
1
| $('#time').datepicker('hide');
|
更新日期选择器
将文本框内的日期更新到日期选择器
1
| $('#time').datepicker('update');
|
指定更新的日期
1 2 3 4 5
| $('#time').datepicker('update', '2012-12-12'); $('#time').datepicker('update', '2012-12-12', '2012-12-12');
$('#time').datepicker('update', new Date(2012, 12, 12)); $('#time').datepicker('update', [new Date(2012, 12, 12), new Date(2012, 12, 12)]);
|
重置日期选择器
1
| $('#time').datepicker('update', ' ');
|
绑定事件
日期选择器显示
1 2 3
| $('#time').datepicker().on('show', function(e){ ... });
|
日期选择器隐藏
日期改变事件
1 2 3
| $('#time').datepicker().on('hide', function(e){ ... });
|
日期改变事件
1 2 3
| $('#time').datepicker().on('changeDate', function(e){ console.log(e.date.valueOf()); });
|
年视图被改变
1 2 3
| $('#time').datepicker().on('changeYear', function(e){ ... });
|
月视图被改变
1 2 3
| $('#time').datepicker().on('changeMonth', function(e){ ... });
|
设置日期区间选择器
1 2 3 4 5 6 7 8 9 10 11
| <input type="text" id="startTime"> <input type="text" id="endTime">
<script> $('#startTime').datepicker().on('change', function(e){ $('#endTime').datepicker('setStartDate', $('#startTime').val()); }); $('#endTime').datepicker().on('change', function(e){ $('#startTime').datepicker('setEndDate', $('#endTime').val()); }); </script>
|
完成
参考文献
bootstrap-timepicker官方文档
bootstrap-datetimepicker官网
IT小书童——bootstrap-datepicker中文文档
CSDN——Tessa_zzl