日期選擇器是表單中最高頻組件之一。本文實現一個零依賴、支援範圍限制、正確處理閏年的年/月/日三級聯動選擇器,代碼精簡且易於集成。
/**
* 根據年份、月份返回該月天數
* @param {Number} year - 年份
* @param {Number} month - 月份 (1-12)
* @returns {Number} 天數
*/
function getDaysInMonth(year, month) {
// 閏年判斷:能被4整除但不能被100整除,或能被400整除
const isLeap = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
const febDays = isLeap ? 29 : 28;
// 月份天數映射
const daysMap = {
1: 31, 2: febDays, 3: 31, 4: 30, 5: 31, 6: 30,
7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
};
return daysMap[month] || 31;
}
/**
* 日期三級聯動組件
* @param {Object} opt - 配置項
* @param {String} opt.targets - 三個 select 的 ID,格式 "#year,#month,#day"
* @param {String} opt.range - 日期範圍 "YYYY-MM-DD,YYYY-MM-DD"
*/
function GySetDate(opt) {
// 解析目標元素
const [yId, mId, dId] = opt.targets.split(',').map(s => s.trim().slice(1));
this.eYear = document.getElementById(yId);
this.eMonth = document.getElementById(mId);
this.eDay = document.getElementById(dId);
if (!this.eYear || !this.eMonth || !this.eDay) return;
// 解析範圍
const [startStr, endStr] = opt.range.split(',');
const [sy, sm, sd] = startStr.split('-').map(Number);
const [ey, em, ed] = endStr.split('-').map(Number);
this.range = { start: { y: sy, m: sm, d: sd }, end: { y: ey, m: em, d: ed } };
this.init();
}
GySetDate.prototype = {
init() {
this.fillYears();
this.bindEvents();
// 初始化月份和日期
this.onYearChange(this.range.start.y);
},
fillYears() {
const { start, end } = this.range;
this.eYear.innerHTML = '';
for (let y = start.y; y <= end.y; y++) {
this.eYear.add(new Option(y, y));
}
},
fillMonths(year, startMonth = 1, endMonth = 12) {
this.eMonth.innerHTML = '';
for (let m = startMonth; m <= endMonth; m++) {
const val = m < 10 ? '0' + m : m;
this.eMonth.add(new Option(val, val));
}
},
fillDays(year, month, startDay = 1, endDay = null) {
this.eDay.innerHTML = '';
const maxDay = endDay || getDaysInMonth(year, month);
for (let d = startDay; d <= maxDay; d++) {
const val = d < 10 ? '0' + d : d;
this.eDay.add(new Option(val, val));
}
},
onYearChange(year) {
const { start, end } = this.range;
if (year === start.y) {
this.fillMonths(year, start.m);
this.fillDays(year, start.m, start.d);
} else if (year === end.y) {
this.fillMonths(year, 1, end.m);
this.fillDays(year, 1, 1, end.m === 1 ? end.d : null);
} else {
this.fillMonths(year);
this.fillDays(year, 1);
}
},
onMonthChange() {
const year = +this.eYear.value;
const month = +this.eMonth.value;
const { start, end } = this.range;
if (year === end.y && month === end.m) {
this.fillDays(year, month, 1, end.d);
} else if (year === start.y && month === start.m) {
this.fillDays(year, month, start.d);
} else {
this.fillDays(year, month);
}
},
bindEvents() {
this.eYear.onchange = () => this.onYearChange(+this.eYear.value);
this.eMonth.onchange = () => this.onMonthChange();
}
};
// 工具函數
function getDaysInMonth(year, month) {
const isLeap = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
if (month === 2) return isLeap ? 29 : 28;
if ([1,3,5,7,8,10,12].includes(month)) return 31;
return 30;
}
<select id="year"></select>
<select id="month"></select>
<select id="day"></select>
<script>
new GySetDate({
targets: '#year,#month,#day',
range: '2020-01-01,2030-12-31'
});
</script>
這組件體積極小(<2KB),適合嵌入式、移動端、無框架項目直接使用。