表單需三個 `
class DateLinkage {
constructor({ yearSel, monthSel, daySel, range = 30 } = {}) {
this.$year = document.querySelector(yearSel);
this.$month = document.querySelector(monthSel);
this.$day = document.querySelector(daySel);
this.range = range;
this.monHead = [31,28,31,30,31,30,31,31,30,31,30,31];
this.init();
}
init() {
const now = new Date();
const y = now.getFullYear();
const m = now.getMonth() + 1;
const d = now.getDate();
this.fillYears(y);
this.fillMonths();
this.$year.value = y;
this.$month.value = m;
this.updateDays(m, y);
this.$day.value = d;
// 綁定事件
this.$year.addEventListener("change", () => this.onYearChange());
this.$month.addEventListener("change", () => this.onMonthChange());
}
fillYears(currentYear) {
const frag = document.createDocumentFragment();
const start = currentYear - this.range;
const end = currentYear + this.range;
for (let y = start; y <= end; y++) {
const opt = document.createElement("option");
opt.value = y; opt.textContent = `${y} 年`;
frag.appendChild(opt);
}
this.$year.innerHTML = ``;
this.$year.appendChild(frag);
}
fillMonths() {
const frag = document.createDocumentFragment();
for (let m = 1; m <= 12; m++) {
const opt = document.createElement("option");
opt.value = m; opt.textContent = `${m} 月`;
frag.appendChild(opt);
}
this.$month.innerHTML = ``;
this.$month.appendChild(frag);
}
isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
getDaysInMonth(year, month) {
if (month === 2) return this.isLeapYear(year) ? 29 : 28;
return this.monHead[month - 1];
}
updateDays(month, year) {
const days = this.getDaysInMonth(year, month);
const frag = document.createDocumentFragment();
for (let d = 1; d <= days; d++) {
const opt = document.createElement("option");
const val = String(d).padStart(2, "0");
opt.value = val; opt.textContent = `${val} 日`;
frag.appendChild(opt);
}
this.$day.innerHTML = ``;
this.$day.appendChild(frag);
}
onYearChange() {
const y = parseInt(this.$year.value, 10);
const m = parseInt(this.$month.value, 10);
if (!y || !m) return;
this.updateDays(m, y);
}
onMonthChange() {
const m = parseInt(this.$month.value, 10);
const y = parseInt(this.$year.value, 10);
if (!m || !y) { this.$day.innerHTML = ``; return; }
this.updateDays(m, y);
}
}
// 使用
new DateLinkage({
yearSel: "#year",
monthSel: "#month",
daySel: "#day",
range: 30
});
<div class="date-picker">
<select id="year"></select>
<select id="month"></select>
<select id="day"></select>
</div>
日期聯動核心在於 **閏年判斷 + 月份天數查表 + 事件聯動更新日選單**。封裝為 Class 可復用、隔離狀態。現代專案優先用 ``,僅在相容性要求下採用三選單方案。