萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JS 經典特效:日歷生成器實現原理與現代重寫

功能描述

根據年、月生成月曆表格,支持:

  • 顯示星期標題(可選長/短/縮寫)
  • 正確計算每月天數、首日星期
  • 當前日期高亮
  • 點擊選中日期、懸停變色
  • 下拉框切換年月動態更新

核心算法:構建月曆數據


/**
 * 構建指定年月的月曆二維數組
 * @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;
}

渲染器(原版:document.write → 現代:DOM 構建)


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 += ``);
        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 += ``;
            });
            html += '';
        });
        html += '
${label}
${day ? `${day}` : ''}
'; 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)); });

CSS 樣式


.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; }

HTML 容器


原版代碼特點(歷史視角)

  • 使用 document.write 直接輸出 HTML(阻塞、難維護)
  • 全局變量 calDateText、objPrevElement 管理狀態
  • fBuildCal 返回二維數組,邏輯清晰可復用
  • fUpdateCal 通過直接操作 innerText 更新單元格(性能尚可)
  • 依賴 IE 專有 for=window event=onload 腳本塊

總結

日曆生成器核心是**日期計算算法**(首日星期、月天數)與**表格渲染**的分離。現代重寫採用 **ES6 Class 封裝、構建函數純邏輯無副作用、DOM API 構建 HTML、事件委託、CustomEvent 解耦**、**Intl.DateTimeFormat** 可進一步國際化。原版 fBuildCal 算法思想仍具參考價值。

copyright © 萬盛學電腦網 all rights reserved