實現「開始日期 - 結束日期」區間選擇:用戶點擊輸入框彈出雙月曆,第一次點擊選開始日期,第二次選結束日期,自動填充「開始日期 至 結束日期」格式。
$.datepicker,設置 numberOfMonths: 2 顯示雙月曆firstDate 暫存首次選擇的日期onSelect 回調中判斷是第幾次選擇,處理日期順序、驗證、格式化_hideDatepicker 實現「選擇結束日期後自動關閉」<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>日期區間選擇</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script>
// 中文化配置
$.datepicker.regional['zh-CN'] = {
closeText: '關閉', prevText: '<上月', nextText: '下月>',
currentText: '今天', monthNames: ['一月','二月','三月','四月','五月','六月',
'七月','八月','九月','十月','十一月','十二月'],
monthNamesShort: ['一月','二月','三月','四月','五月','六月',
'七月','八月','九月','十月','十一月','十二月'],
dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
dayNamesMin: ['日','一','二','三','四','五','六'],
weekHeader: '周', dateFormat: 'yy-mm-dd', firstDay: 1,
isRTL: false, showMonthAfterYear: true, yearSuffix: '年'
};
$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
$(function() {
let firstDate = null; // 暫存首次選擇
$('#dateRange').datepicker({
numberOfMonths: 2, // 雙月曆
showMonthAfterYear: true,
showButtonPanel: true,
autoClose: true, // 自定義屬性,配合下方修改
onSelect: function(dateText, inst) {
if (!firstDate) {
// 第一次選擇:記錄開始日期
firstDate = dateText;
$(this).val(firstDate + ' 至...');
// 防止面板關閉(需配合修改 _hideDatepicker)
inst.autoClose = false;
} else {
// 第二次選擇:確定結束日期
const [start, end] = [firstDate, dateText].sort(); // 自動排序
$(this).val(`${start} 至 ${end}`);
firstDate = null;
inst.autoClose = true; // 允許關閉
}
},
onClose: function() {
// 面板關閉時重置(用戶點擊關閉按鈕或失焦)
if (firstDate) {
$(this).val(firstDate + ' 至...');
}
}
});
// 修改 datepicker 內部 _hideDatepicker 支持 autoClose 控制
// 注意:修改內部方法屬於 Hack,升級 jQuery UI 可能失效
const originalHide = $.datepicker._hideDatepicker;
$.datepicker._hideDatepicker = function(input) {
const inst = this._curInst;
if (inst && inst.autoClose === false) return; // 阻止關閉
originalHide.call(this, input);
};
});
</script>
</head>
<body>
日期區間:<input id="dateRange" style="width: 220px; height: 30px;" readonly>
</body>
</html>
numberOfMonths: 2:顯示兩個月曆,便於跨月選擇firstDate 閉包變量:記錄首次選擇,實現兩步選擇流程.sort() 自動處理日期順序:用戶可先選結束日期再選開始日期autoClose 自定義屬性 + _hideDatepicker Hack:控制面板關閉時機readonly 輸入框:防止手動輸入破壞格式jQuery UI 已停止積極維護,新項目建議使用:
mode: "range"<input type="date"> + JS 處理邏輯(無依賴)<input id="range" placeholder="選擇日期區間">
flatpickr('#range', {
mode: 'range',
locale: 'zh',
dateFormat: 'Y-m-d',
onClose: (dates) => {
if (dates.length === 2) {
console.log('區間:', dates[0], '至', dates[1]);
}
}
});
理解 jQuery UI Datepicker 的區間選擇邏輯有助於維護舊項目,但新項目強烈建議採用現代、活躍維護的替代庫。