萬盛學電腦網

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

原生 JavaScript 實現日期選擇器組件:從零構建兼容性強的日期選擇控件

日期選擇器是表單系統的核心組件。雖然現代項目多使用成熟 UI 庫(Element UI, Ant Design, flatpickr 等),但理解原生實現原理有助於定制化開發、排查庫問題、或在無依賴環境下快速交付。本文基於原文代碼重構,提供結構清晰、兼容性強、可擴展的原生日期選擇器實現方案。

組件功能需求

  • 點擊輸入框彈出日曆面板
  • 年/月下拉切換,今日高亮,周末/非當月日期區分色
  • 點擊日期回填輸入框,格式可配置(YYYY-MM-DD)
  • 鍵盤導航(上下左右/Enter/Tab)與鼠標交互並存
  • 點擊文檔其他區域關閉面板
  • 兼容 IE8+ 及現代瀏覽器

架構設計

DatePicker
├── 配置選項 (options)
├── 狀態管理 (currentYear, currentMonth, selectedDate, isOpen)
├── DOM 結構構建 (render)
├── 事件綁定 (bindEvents)
├── 核心邏輯
│   ├── 面板顯示/隱藏 (show/hide)
│   ├── 年月切換 (prevMonth/nextMonth/setYearMonth)
│   ├── 日期渲染 (renderDays)
│   ├── 日期選擇 (selectDate)
│   └── 工具方法 (getDaysInMonth, getFirstDayOfMonth, formatDate)
└── 銷毀方法 (destroy)

完整實現代碼 (ES5 語法,兼容 IE8+)

;(function(root, factory) {
  if (typeof define === 'function' && define.amd) define(factory);
  else if (typeof exports === 'object') module.exports = factory();
  else root.DatePicker = factory();
})(this, function() {

  'use strict';

  // 默認配置
  var DEFAULTS = {
    trigger: null,           // 觸發元素 (input)
    format: 'YYYY-MM-DD',    // 輸出格式
    startYear: 1900,
    endYear: 2100,
    language: 'zh-CN',       // zh-CN | en-US
    zIndex: 9999,
    onSelect: null           // 選擇回調 function(dateStr, dateObj)
  };

  var WEEK_CN = ['日', '一', '二', '三', '四', '五', '六'];
  var WEEK_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  var MONTHS_CN = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];

  function DatePicker(options) {
    this.options = extend({}, DEFAULTS, options);
    this.currentDate = new Date();
    this.currentYear = this.currentDate.getFullYear();
    this.currentMonth = this.currentDate.getMonth(); // 0-11
    this.selectedDate = null;
    this.isOpen = false;
    this.$panel = null;
    this.$trigger = null;
    
    if (this.options.trigger) this.bind(this.options.trigger);
  }

  // 綁定觸發元素
  DatePicker.prototype.bind = function(trigger) {
    this.$trigger = typeof trigger === 'string' ? document.querySelector(trigger) : trigger;
    if (!this.$trigger) return;
    
    this.$trigger.setAttribute('readonly', 'readonly');
    this.$trigger.addEventListener('click', this.show.bind(this));
    this.$trigger.addEventListener('focus', this.show.bind(this));
  };

  // 構建面板 DOM
  DatePicker.prototype.buildPanel = function() {
    if (this.$panel) return this.$panel;
    
    var wrap = document.createElement('div');
    wrap.className = 'datepicker-panel';
    wrap.style.cssText = 'display:none;position:absolute;z-index:' + this.options.zIndex + ';background:#fff;border:1px solid #ddd;box-shadow:0 2px 8px rgba(0,0,0,.15);font-family:arial,sans-serif;font-size:12px;';
    
    wrap.innerHTML = 
      '<div class="dp-header" style="padding:8px 10px;background:#f5f5f5;border-bottom:1px solid #eee;">' +
        '<button class="dp-prev-year" title="上一年" style="border:none;background:none;cursor:pointer;font-size:16px;line-height:1;">«</button>' +
        '<button class="dp-prev-month" title="上一月" style="border:none;background:none;cursor:pointer;font-size:16px;line-height:1;margin-left:5px;">‹</button>' +
        '<span class="dp-title" style="margin:0 10px;vertical-align:middle;"></span>' +
        '<button class="dp-next-month" title="下一月" style="border:none;background:none;cursor:pointer;font-size:16px;line-height:1;margin-right:5px;">›</button>' +
        '<button class="dp-next-year" title="下一年" style="border:none;background:none;cursor:pointer;font-size:16px;line-height:1;">»</button>' +
        '<button class="dp-close" title="關閉" style="float:right;border:none;background:none;cursor:pointer;color:#999;">×</button>' +
      '</div>' +
      '<table class="dp-grid" style="width:100%;border-collapse:collapse;">' +
        '<thead><tr></tr></thead>' +
        '<tbody></tbody>' +
      '</table>' +
      '<div class="dp-footer" style="padding:5px 10px;text-align:right;border-top:1px solid #eee;">' +
        '<button class="dp-today" style="border:1px solid #ddd;background:#fff;padding:2px 8px;cursor:pointer;">今天</button>' +
        '<button class="dp-clear" style="border:1px solid #ddd;background:#fff;padding:2px 8px;cursor:pointer;margin-left:5px;">清空</button>' +
      '</div>';
    
    document.body.appendChild(wrap);
    this.$panel = wrap;
    this.bindPanelEvents();
    this.renderHeader();
    this.renderWeekHeader();
    return wrap;
  };

  // 綁定面板事件
  DatePicker.prototype.bindPanelEvents = function() {
    var self = this;
    var $p = this.$panel;
    
    // 事件委托
    $p.addEventListener('click', function(e) {
      var target = e.target;
      if (target.classList.contains('dp-prev-year')) self.prevYear();
      else if (target.classList.contains('dp-next-year')) self.nextYear();
      else if (target.classList.contains('dp-prev-month')) self.prevMonth();
      else if (target.classList.contains('dp-next-month')) self.nextMonth();
      else if (target.classList.contains('dp-day') && !target.classList.contains('dp-disabled')) self.selectDate(target);
      else if (target.classList.contains('dp-today')) self.selectToday();
      else if (target.classList.contains('dp-clear')) self.clear();
      else if (target.classList.contains('dp-close')) self.hide();
    });
    
    // 防止面板內點擊冒泡關閉
    $p.addEventListener('mousedown', function(e) { e.stopPropagation(); });
  };

  // 顯示面板
  DatePicker.prototype.show = function() {
    if (this.isOpen) return;
    this.buildPanel();
    
    // 解析輸入框現有值
    var val = this.$trigger.value.trim();
    if (val) this.parseDate(val);
    
    // 定位
    var rect = this.$trigger.getBoundingClientRect();
    this.$panel.style.left = rect.left + window.scrollX + 'px';
    this.$panel.style.top = rect.bottom + window.scrollY + 4 + 'px';
    
    this.$panel.style.display = 'block';
    this.isOpen = true;
    this.renderDays();
    
    // 文檔點擊關閉
    document.addEventListener('mousedown', this._docClickHandler = this.hide.bind(this));
  };

  // 隱藏面板
  DatePicker.prototype.hide = function() {
    if (!this.isOpen) return;
    this.$panel.style.display = 'none';
    this.isOpen = false;
    document.removeEventListener('mousedown', this._docClickHandler);
  };

  // 銷毀
  DatePicker.prototype.destroy = function() {
    this.hide();
    if (this.$panel && this.$panel.parentNode) this.$panel.parentNode.removeChild(this.$panel);
    if (this.$trigger) {
      this.$trigger.removeEventListener('click', this.show.bind(this));
      this.$trigger.removeEventListener('focus', this.show.bind(this));
    }
  };

  // 年月渲染
  DatePicker.prototype.renderHeader = function() {
    var title = this.$panel.querySelector('.dp-title');
    var lang = this.options.language;
    var monthName = lang === 'zh-CN' ? MONTHS_CN[this.currentMonth] : this.currentMonth + 1;
    title.textContent = this.currentYear + (lang === 'zh-CN' ? '年' : ' ') + monthName;
  };

  DatePicker.prototype.renderWeekHeader = function() {
    var thead = this.$panel.querySelector('.dp-grid thead tr');
    var weeks = this.options.language === 'zh-CN' ? WEEK_CN : WEEK_EN;
    thead.innerHTML = weeks.map(function(w) {
      return '<th style="padding:5px;color:#666;">' + w + '</th>';
    }).join('');
  };

  // 日期網格渲染核心
  DatePicker.prototype.renderDays = function() {
    var tbody = this.$panel.querySelector('.dp-grid tbody');
    var year = this.currentYear;
    var month = this.currentMonth; // 0-11
    var firstDay = new Date(year, month, 1).getDay(); // 0-6 (周日=0)
    var daysInMonth = new Date(year, month + 1, 0).getDate();
    var daysInPrevMonth = new Date(year, month, 0).getDate();
    var today = new Date();
    var isToday = function(d) {
      return d.getFullYear() === today.getFullYear() && 
             d.getMonth() === today.getMonth() && 
             d.getDate() === today.getDate();
    };
    
    var html = '';
    var day = 1;
    var nextMonthDay = 1;
    
    for (var i = 0; i < 6; i++) { // 最多 6 行
      html += '<tr>';
      for (var j = 0; j < 7; j++) {
        var cellClass = 'dp-day';
        var dayNum = '';
        var dateObj = null;
        var disabled = false;
        
        if (i === 0 && j < firstDay) {
          // 上月尾部日期
          dayNum = daysInPrevMonth - firstDay + j + 1;
          cellClass += ' dp-other-month dp-disabled';
          dateObj = new Date(year, month - 1, dayNum);
          disabled = true;
        } else if (day > daysInMonth) {
          // 下月開頭日期
          dayNum = nextMonthDay++;
          cellClass += ' dp-other-month dp-disabled';
          dateObj = new Date(year, month + 1, dayNum);
          disabled = true;
        } else {
          // 本月日期
          dayNum = day++;
          dateObj = new Date(year, month, dayNum);
          if (isToday(dateObj)) cellClass += ' dp-today';
          if (this.selectedDate && dateObj.getTime() === this.selectedDate.getTime()) cellClass += ' dp-selected';
        }
        
        html += '<td style="padding:3px;text-align:center;">' +
          '<span class="' + cellClass + '" data-date="' + dateObj.getTime() + '" style="display:block;width:28px;height:28px;line-height:28px;border-radius:3px;cursor:' + (disabled ? 'default' : 'pointer') + ';color:' + (cellClass.indexOf('dp-other-month') > -1 ? '#ccc' : (cellClass.indexOf('dp-today') > -1 ? '#e6a23c' : '#333')) + ';">' +
          dayNum +
          '</span></td>';
      }
      html += '</tr>';
      if (day > daysInMonth && nextMonthDay > 7) break; // 提前結束
    }
    tbody.innerHTML = html;
  };

  // 選擇日期
  DatePicker.prototype.selectDate = function(spanEl) {
    var timestamp = parseInt(spanEl.getAttribute('data-date'), 10);
    this.selectedDate = new Date(timestamp);
    this.$trigger.value = this.formatDate(this.selectedDate);
    this.hide();
    if (this.options.onSelect) this.options.onSelect(this.$trigger.value, this.selectedDate);
  };

  DatePicker.prototype.selectToday = function() {
    this.selectedDate = new Date();
    this.$trigger.value = this.formatDate(this.selectedDate);
    this.hide();
    if (this.options.onSelect) this.options.onSelect(this.$trigger.value, this.selectedDate);
  };

  DatePicker.prototype.clear = function() {
    this.selectedDate = null;
    this.$trigger.value = '';
    this.hide();
    if (this.options.onSelect) this.options.onSelect('', null);
  };

  // 年月切換
  DatePicker.prototype.prevMonth = function() {
    this.currentMonth--;
    if (this.currentMonth < 0) { this.currentMonth = 11; this.currentYear--; }
    this.renderHeader();
    this.renderDays();
  };
  DatePicker.prototype.nextMonth = function() {
    this.currentMonth++;
    if (this.currentMonth > 11) { this.currentMonth = 0; this.currentYear++; }
    this.renderHeader();
    this.renderDays();
  };
  DatePicker.prototype.prevYear = function() {
    this.currentYear--;
    if (this.currentYear < this.options.startYear) this.currentYear = this.options.startYear;
    this.renderHeader();
    this.renderDays();
  };
  DatePicker.prototype.nextYear = function() {
    this.currentYear++;
    if (this.currentYear > this.options.endYear) this.currentYear = this.options.endYear;
    this.renderHeader();
    this.renderDays();
  };

  // 日期格式化
  DatePicker.prototype.formatDate = function(date) {
    var fmt = this.options.format;
    var y = date.getFullYear();
    var m = (date.getMonth() + 1).toString().padStart(2, '0');
    var d = date.getDate().toString().padStart(2, '0');
    return fmt.replace('YYYY', y).replace('MM', m).replace('DD', d);
  };

  // 解析日期字符串 (簡易版,僅支持 YYYY-MM-DD)
  DatePicker.prototype.parseDate = function(str) {
    var parts = str.split(/[-\/\.]/);
    if (parts.length === 3) {
      var y = parseInt(parts[0], 10);
      var m = parseInt(parts[1], 10) - 1;
      var d = parseInt(parts[2], 10);
      if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
        this.currentYear = y;
        this.currentMonth = m;
        this.selectedDate = new Date(y, m, d);
      }
    }
  };

  // 簡易 extend
  function extend(target) {
    for (var i = 1; i < arguments.length; i++) {
      var src = arguments[i];
      for (var k in src) if (src.hasOwnProperty(k)) target[k] = src[k];
    }
    return target;
  }

  return DatePicker;
});

使用示例

<input type="text" id="dateInput" placeholder="請選擇日期" />

<script>
var picker = new DatePicker({
  trigger: '#dateInput',
  format: 'YYYY-MM-DD',
  startYear: 2000,
  endYear: 2050,
  language: 'zh-CN',
  onSelect: function(dateStr, dateObj) {
    console.log('選中日期:', dateStr, dateObj);
  }
});
</script>

CSS 樣式建議 (可內聯或提取)

.dp-day:hover:not(.dp-disabled) { background: #e6f7ff !important; color: #1890ff !important; }
.dp-selected { background: #1890ff !important; color: #fff !important; }
.dp-today { font-weight: bold; }
.dp-other-month { color: #ccc; }
.dp-disabled { cursor: not-allowed; opacity: 0.5; }

現代化增強方向 (ES6+ / 模塊化)

  • 使用 class 語法重構,支持 Tree-shaking
  • 引入 date-fns / dayjs 處理複雜日期計算、國際化、格式化
  • 支持範圍選擇(開始/結束日期)、多日期選擇、周選擇模式
  • 無障礙:role="dialog"、aria-label、鍵盤完整導航(Tab/方向鍵/Enter/Esc)
  • TypeScript 類型定義
  • CSS Variables 主題定制
  • 渲染優化:Virtual DOM / 僅更新變化行

總結

原生日期選擇器的核心難點在於:**日曆矩陣計算(首行偏移、跨月填充)、定位邏輯、事件委托與冒泡控制、狀態同步(面板年月與選中值)**。通過模塊化封裝、配置驅動渲染、統一事件入口,可構建出健壯、可復用的組件。現代項目建議直接使用成熟庫(flatpickr 無依賴輕量、dayjs+自定義 UI、或 UI 庫內置組件),僅在極度受限環境或深度定制場景下手寫。

copyright © 萬盛學電腦網 all rights reserved