jQuery UI Datepicker(日期选择器)实例
Datepicker是 jQuery UI 最受欢迎的组件之一,用于在输入框中弹出日历选择日期,支持本地化、日期范围限制、自定义格式、多月显示、动画等。非常适合表单中的出生日期、预约日期、行程选择等场景。
官方演示地址:https://jqueryui.com/datepicker/
下面提供几个渐进实例,从基础到高级,代码使用最新 CDN,可直接复制到 HTML 文件测试。
1.基础日期选择器
点击输入框弹出日历。
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>jQuery UI Datepicker 基础示例</title><linkrel="stylesheet"href="//code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css"><scriptsrc="//code.jquery.com/jquery-3.6.0.min.js"></script><scriptsrc="//code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script></head><body><label>选择日期:</label><inputtype="text"id="datepicker"><script>$(function(){$("#datepicker").datepicker();});</script></body></html>2.中文本地化 + 常用选项(格式、切换年月、默认日期)
<script>$("#datepicker").datepicker({dateFormat:"yy-mm-dd",// 日期格式(yy=四位年,mm=两位月,dd=两位日)changeMonth:true,// 显示月份下拉changeYear:true,// 显示年份下拉yearRange:"1900:2030",// 年份范围showAnim:"fadeIn",// 显示动画defaultDate:"2000-01-01",// 默认日期// 中文本地化monthNames:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],monthNamesShort:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],dayNames:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],dayNamesShort:["周日","周一","周二","周三","周四","周五","周六"],dayNamesMin:["日","一","二","三","四","五","六"],firstDay:1// 周一作为一周开始});</script>3.日期范围限制(minDate/maxDate) + 内联显示
- 内联:直接显示日历而不绑定输入框。
<!-- 绑定输入框 + 范围限制 --><inputtype="text"id="datepicker-range"><!-- 内联日历 --><divid="inline-datepicker"></div><script>$("#datepicker-range").datepicker({minDate:0,// 今天及以后maxDate:"+1m +10d"// 最多提前1个月10天});$("#inline-datepicker").datepicker({numberOfMonths:2,// 显示两个月showButtonPanel:true// 显示“今天”和“关闭”按钮});</script>4.多日期选择 + 事件监听
<script>$("#datepicker").datepicker({numberOfMonths:3,// 显示三个月showOtherMonths:true,// 显示相邻月日期selectOtherMonths:true,// 可选择相邻月onSelect:function(dateText,inst){console.log("选中日期:"+dateText);}});</script>5.自定义图标触发 + 多个输入框(出发/返回日期)
<inputtype="text"id="depart">到<inputtype="text"id="return"><script>$("#depart, #return").datepicker({showOn:"both",// 点击输入框或按钮都显示buttonImage:"https://jqueryui.com/resources/images/calendar.gif",buttonImageOnly:true,buttonText:"选择日期"});// 出发日期选择后,返回日期最小为出发后一天$("#depart").datepicker("option","onSelect",function(selectedDate){$("#return").datepicker("option","minDate",selectedDate);});</script>小技巧:
- 完整本地化文件:可引入
jquery-ui-i18n支持更多语言。 - 主题切换:替换 CSS 如
base、dark-hive等(https://jqueryui.com/themeroller/)。 - 移动端:默认支持触摸,但可加
$.datepicker.setDefaults({ showOn: "focus" });优化。
如果你需要日期范围选择器(两个输入框联动)、带时间的选择器(需额外插件)、或自定义主题示例,请告诉我更多需求!