萬盛學電腦網

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

JavaScript 生日聯動選單與星座自動顯示:年月日級聯、閏年修正、星座即時更新

功能需求

  1. 年、月、日三級下拉選單聯動
  2. 月份變更時自動修正日期上限(含閏年 2 月)
  3. 月、日變更時即時顯示對應星座

核心工具函式


// 取得指定年月的天數
function getDaysInMonth(year, month) {
  const days = [31,28,31,30,31,30,31,31,30,31,30,31];
  if (month === 2) {
    return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28;
  }
  return days[month - 1];
}

// 星座判斷(資料驅動)
const ZODIAC = [
  { name: "魔羯座", start: [12,22], end: [1,19] },
  { name: "水瓶座", start: [1,20], end: [2,18] },
  { name: "雙魚座", start: [2,19], end: [3,20] },
  { name: "白羊座", start: [3,21], end: [4,19] },
  { name: "金牛座", start: [4,21], end: [5,21] },
  { name: "雙子座", start: [5,22], end: [6,21] },
  { name: "巨蟹座", start: [6,22], end: [7,22] },
  { name: "獅子座", start: [7,23], end: [8,23] },
  { name: "處女座", start: [8,24], end: [9,23] },
  { name: "天秤座", start: [9,24], end: [10,23] },
  { name: "天蠍座", start: [10,24], end: [11,22] },
  { name: "射手座", start: [11,23], end: [12,21] },
];

function getZodiac(month, day) {
  if ((month === 12 && day >= 22) || (month === 1 && day <= 19)) return "魔羯座";
  for (const z of ZODIAC) {
    if (z.name === "魔羯座") continue;
    const [sm, sd] = z.start, [em, ed] = z.end;
    if ((month === sm && day >= sd) || (month === em && day <= ed)) return z.name;
  }
  return "";
}

選單初始化與聯動邏輯


function initBirthdaySelects(yearSel, monthSel, daySel, zodiacSel) {
  const $y = $(yearSel), $m = $(monthSel), $d = $(daySel), $z = $(zodiacSel);
  const now = new Date();
  const cy = now.getFullYear(), cm = now.getMonth() + 1, cd = now.getDate();

  // 填充年份(近 100 年)
  for (let y = cy - 100; y <= cy; y++) $y.append(``);
  $y.val(cy);

  // 填充月份
  for (let m = 1; m <= 12; m++) $m.append(``);
  $m.val(cm);

  // 更新日期
  function updateDays() {
    const y = +$y.val(), m = +$m.val();
    if (!y || !m) { $d.html(''); return; }
    const days = getDaysInMonth(y, m);
    const cur = $d.val();
    $d.html('');
    for (let i = 1; i <= days; i++) $d.append(``);
    $d.val(Math.min(cd, days)); // 修正超出天數
  }

  // 更新星座
  function updateZodiac() {
    const m = +$m.val(), d = +$d.val();
    $z.text(m && d ? getZodiac(m, d) : "");
  }

  // 事件綁定
  $y.on("change", () => { updateDays(); updateZodiac(); });
  $m.on("change", () => { updateDays(); updateZodiac(); });
  $d.on("change", updateZodiac);

  // 初始化
  updateDays();
  updateZodiac();
}

// 使用
initBirthdaySelects("#DDL_Year", "#DDL_Month", "#DDL_Day", "#astro");

HTML 結構


進階優化

  • 記憶體優化:用 `DocumentFragment` 批次建立 `
  • 無障礙:`
  • 原生 `` 降級**

if ("showPicker" in HTMLInputElement.prototype) {
  // 支援原生日期選擇器
  document.getElementById("nativeDate").style.display = "block";
  document.getElementById("fallbackSelects").style.display = "none";
}

總結

生日聯動核心:**年月決定日上限(閏年邏輯) + 月日決定星座(查表法)**。封裝為可復用函式,配合事件聯動與原生日期輸入降級,兼顧體驗與相容性。

copyright © 萬盛學電腦網 all rights reserved