根據年、月生成月曆表格,支持:
/**
* 構建指定年月的月曆二維數組
* @param {number} year - 年份 (如 2024)
* @param {number} month - 月份 1-12
* @returns {Array>} 6行 x 7列,null 表示空白
*/
function buildCalendar(year, month) {
// 1. 獲取該月 1 號是星期幾 (0=日, 6=六)
const firstDay = new Date(year, month - 1, 1).getDay();
// 2. 獲取該月總天數
const daysInMonth = new Date(year, month, 0).getDate();
const weeks = [];
let day = 1;
// 生成 6 行(最多 6 週)
for (let w = 0; w < 6; w++) {
const week = [];
for (let d = 0; d < 7; d++) {
if (w === 0 && d < firstDay) {
week.push(null); // 首行前導空白
} else if (day > daysInMonth) {
week.push(null); // 尾部空白
} else {
week.push(day++);
}
}
weeks.push(week);
if (day > daysInMonth) break; // 提前結束
}
return weeks;
}
class CalendarRenderer {
constructor(container, options = {}) {
this.container = typeof container === 'string' ? document.querySelector(container) : container;
this.options = {
cellWidth: '100px',
cellHeight: '80px',
dateFontSize: '14px',
dateFontWeight: 'bold',
dayStyle: 1, // 0:Su, 1:Mon, 2:Monday
...options
};
this.selectedDateEl = null;
this._initSelectors();
}
_initSelectors() {
// 年月下拉框
this.yearSel = this.container.querySelector('[data-year]');
this.monthSel = this.container.querySelector('[data-month]');
if (this.yearSel && this.monthSel) {
this._populateSelectors();
this.yearSel.addEventListener('change', () => this.render());
this.monthSel.addEventListener('change', () => this.render());
}
}
_populateSelectors() {
const now = new Date();
// 年份:當前年 ±10 年
for (let y = now.getFullYear() - 10; y <= now.getFullYear() + 10; y++) {
this.yearSel.add(new Option(y, y, false, y === now.getFullYear()));
}
// 月份
const months = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
months.forEach((m, i) => this.monthSel.add(new Option(m, i+1, false, i === now.getMonth())));
}
render(year = null, month = null) {
year = year || parseInt(this.yearSel?.value) || new Date().getFullYear();
month = month || parseInt(this.monthSel?.value) || new Date().getMonth() + 1;
const weeks = buildCalendar(year, month);
const dayLabels = this._getDayLabels();
// 構建表格 HTML
let html = '';
dayLabels.forEach(label => html += `${label} `);
html += ' ';
weeks.forEach((week, w) => {
html += '';
week.forEach((day, d) => {
const isToday = this._isToday(year, month, day);
const isSelected = this.selectedDateEl?.dataset.day == day &&
this.selectedDateEl?.dataset.month == month &&
this.selectedDateEl?.dataset.year == year;
html += `
${day ? `${day}` : ''}
`;
});
html += ' ';
});
html += '
';
this.container.innerHTML = html;
this._bindCellEvents();
}
_getDayLabels() {
const styles = {
0: ['Su','Mo','Tu','We','Th','Fr','Sa'],
1: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
2: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
};
return styles[this.options.dayStyle] || styles[1];
}
_isToday(y, m, d) {
if (!d) return false;
const now = new Date();
return y === now.getFullYear() && m === now.getMonth()+1 && d === now.getDate();
}
_bindCellEvents() {
this.container.querySelectorAll('.cal-cell[data-day]').forEach(cell => {
cell.addEventListener('mouseenter', () => cell.classList.add('hover'));
cell.addEventListener('mouseleave', () => cell.classList.remove('hover'));
cell.addEventListener('click', () => this._selectCell(cell));
});
}
_selectCell(cell) {
// 移除舊選中
this.container.querySelectorAll('.cal-cell.selected').forEach(el => el.classList.remove('selected'));
// 標記新選中
cell.classList.add('selected');
this.selectedDateEl = cell;
// 觸發自定義事件
this.container.dispatchEvent(new CustomEvent('dateselect', {
detail: { year: +cell.dataset.year, month: +cell.dataset.month, day: +cell.dataset.day }
}));
}
getSelectedDate() {
if (!this.selectedDateEl) return null;
return {
year: +this.selectedDateEl.dataset.year,
month: +this.selectedDateEl.dataset.month,
day: +this.selectedDateEl.dataset.day
};
}
}
// 使用
document.addEventListener('DOMContentLoaded', () => {
const cal = new CalendarRenderer('#calendar-container');
cal.render();
cal.container.addEventListener('dateselect', e => console.log('選中日期:', e.detail));
});
.cal-table { border-collapse: collapse; width: 100%; font-family: Arial, sans-serif; }
.cal-table th { background: #3498db; color: white; padding: 8px; font-weight: 600; text-align: center; }
.cal-cell { border: 1px solid #eee; width: 100px; height: 80px; vertical-align: top; cursor: pointer; position: relative; }
.cal-cell:hover, .cal-cell.hover { background: #fef9e7; }
.cal-cell.today { background: #ebf5fb; }
.cal-cell.today .cal-date { color: #3498db; font-weight: bold; }
.cal-cell.selected { background: #d5f5e3; outline: 2px solid #27ae60; }
.cal-date { display: block; font-size: 14px; font-weight: bold; padding: 4px; }
document.write 直接輸出 HTML(阻塞、難維護)calDateText、objPrevElement 管理狀態fBuildCal 返回二維數組,邏輯清晰可復用fUpdateCal 通過直接操作 innerText 更新單元格(性能尚可)for=window event=onload 腳本塊日曆生成器核心是**日期計算算法**(首日星期、月天數)與**表格渲染**的分離。現代重寫採用 **ES6 Class 封裝、構建函數純邏輯無副作用、DOM API 構建 HTML、事件委託、CustomEvent 解耦**、**Intl.DateTimeFormat** 可進一步國際化。原版 fBuildCal 算法思想仍具參考價值。