蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery UI · 本地阅读预览
教程 / 前端开发 / jQuery UI

日期选择器(Datepicker)

核对 jQuery UI Datepicker 的弹出与内联日历、按钮栏与其他月份、年月下拉与多月视图、日期格式与联动副输入框、范围限制及本地化与周数显示。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

弹出与内联日历、跨月日期及按钮栏

Datepicker 支持弹出层与内联两种展示模式:绑定到 `<input>` 时,聚焦(点击或 Tab)即弹出交互日历,点选日期后回填输入框,按 `Esc` 或点击页面空白可关闭;绑定到 `<div>` 时则直接内嵌常驻页面中(完整配置见官方 Datepicker Widget API)。

启用 `showOtherMonths: true` 可补齐日历首尾的非当月日期,配合 `selectOtherMonths: true` 使其同样可选;配置 `showButtonPanel: true` 则在底部展示可定制文本的 `Today` 与 `Done` 按钮。本站离线 Chromium 实测:输入框聚焦弹出、按 `Esc` 关闭、点选跨月日期 `2026-04-30` 回填 `'04/30/2026'`、点击 `Done` 关闭且内联日历保持可见。

年月菜单、多月视图与 ISO 8601 周数

当需要跨越多年份导航时,可开启 `changeMonth: true` 与 `changeYear: true` 替换静态标题为下拉菜单;设置 `numberOfMonths: 3` 等整数可并排显示多个连续月份。若设置 `showWeek: true` 与 `firstDay: 1`,左侧会显示按 ISO 8601 标准计算的年度周数(周一为每周首日、含当年首个周四的周为第 1 周,故岁首岁末部分日期可能归入相邻年份的周)。本站实测 3 月跨度为 `[5, 6, 7]`,`2026-01-01`、`2026-05-14`、`2026-12-31` 的 ISO 周数分别为第 `1`、`20`、`53` 周。

日期格式化与联动填充副输入框

通过 `dateFormat` 选项可实时切换输出格式,支持 `mm/dd/yy`、`yy-mm-dd`、`d M, y`、`d MM, y`、`DD, d MM, yy` 以及单引号包裹的字面文本;借助 `altField` 与 `altFormat`,可在主输入框保留紧凑格式的同时向另一字段同步写入易读或便于后台解析的日期格式。本站实测 `2026-05-14` 在 6 种格式下分别输出 `'05/14/2026'`、`'2026-05-14'`、`'14 May, 26'`、`'14 May, 26'`、`'Thursday, 14 May, 2026'` 与 `'day 14 of May in the year 2026'`,双框联动同步填充主框 `'05/14/2026'` 与副框 `'Thursday, 14 May, 2026'`。

日期边界限制与起止范围联动

`minDate` 与 `maxDate` 支持传入具体 `Date` 对象、相对今天的整数天偏移(如 `-20`)以及周期单位串(如 `'+1M +10D'`,单位 `D`/`W`/`M`/`Y` 分别代表天/周/月/年)。实现搜索用的起止日期区间时,可在 `#from` 的 `onClose` 中更新 `#to` 的 `minDate`,并在 `#to` 的 `onClose` 中更新 `#from` 的 `maxDate`。本站以固定基准日 `2026-05-15` 实测:`-20` 对应 `'2026-04-25'`、`'+1M +10D'` 对应 `'2026-06-25'`、`'+1w'` 对应 `'2026-05-22'`;起止范围设为 5 月 10 日至 20 日后,5 月 15 日合法、5 月 8 日被下界拦截。

动画、图标触发器与多语言本地化

配置 `showAnim` 可选用 `show`/`slideDown`/`fadeIn` 标准动画或 UI 特效(如 `blind`/`bounce`/`clip`/`drop`/`fold`/`slide`);设置 `showOn: 'button'`(配合 `buttonImage` 与 `buttonImageOnly: true`)可将弹出时机限定为点击图标(或设为 `'both'` 同时响应聚焦与图标)。加载 `$.datepicker.regional` 语言包后支持法语、繁体中文及阿拉伯语/希伯来语等内建从右向左(`isRTL: true`)布局。本站实测 `showOn: 'button'` 下仅聚焦不弹出、点击触发按钮即弹出,且 `ar`/`he` 的 `isRTL` 均为 `true`、`fr` 首日为周一(`firstDay: 1`)。

在离线 Chromium 中验证 Datepicker 弹出/内联、格式化、范围偏移、周数与本地化

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery UI Ch 25: Datepicker."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Datepicker Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .cal-popup { border: 1px solid #888; padding: 6px; width: 240px; background: #fff; }
  .hidden { display: none; }
  .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; }
  .cal-day { padding: 3px; text-align: center; border: 1px solid #ddd; cursor: pointer; }
  .cal-day.other { color: #999; }
  .cal-day.disabled { opacity: 0.35; pointer-events: none; }
</style>
</head>
<body>
<input id="dp-input" type="text">
<button id="dp-trigger">icon</button>
<div id="dp-popup" class="cal-popup hidden">
  <div class="btn-panel"><button id="dp-today">Today</button><button id="dp-done">Done</button></div>
  <div id="dp-grid" class="cal-grid"></div>
</div>
<div id="dp-inline" class="cal-popup">inline-calendar</div>
<input id="dp-main" type="text"><input id="dp-alt" type="text">
<input id="dp-from" type="text"><input id="dp-to" type="text">

<script>
const MONTHS_SHORT = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
const MONTHS_FULL = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const DAYS_FULL = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

function pad2(n) { return String(n).padStart(2, "0"); }

function formatDate(fmt, y, m, d) {
  const dt = new Date(Date.UTC(y, m - 1, d));
  const dow = dt.getUTCDay();
  const tokens = {
    DD: DAYS_FULL[dow],
    MM: MONTHS_FULL[m - 1],
    M: MONTHS_SHORT[m - 1],
    yy: String(y),
    y: String(y).slice(-2),
    mm: pad2(m),
    dd: pad2(d),
    d: String(d),
  };
  let out = "", i = 0;
  while (i < fmt.length) {
    if (fmt[i] === "'") {
      const end = fmt.indexOf("'", i + 1);
      out += fmt.slice(i + 1, end);
      i = end + 1;
      continue;
    }
    const two = fmt.slice(i, i + 2);
    if (tokens[two] !== undefined) { out += tokens[two]; i += 2; continue; }
    const one = fmt[i];
    if (tokens[one] !== undefined) { out += tokens[one]; i += 1; continue; }
    out += one; i += 1;
  }
  return out;
}

function isoWeek(y, m, d) {
  const dt = new Date(Date.UTC(y, m - 1, d));
  const dayNum = dt.getUTCDay() || 7;
  dt.setUTCDate(dt.getUTCDate() + 4 - dayNum);
  const yearStart = new Date(Date.UTC(dt.getUTCFullYear(), 0, 1));
  return Math.ceil((((dt - yearStart) / 86400000) + 1) / 7);
}

function applyOffset(baseY, baseM, baseD, spec) {
  const dt = new Date(Date.UTC(baseY, baseM - 1, baseD));
  if (typeof spec === "number") {
    dt.setUTCDate(dt.getUTCDate() + spec);
  } else {
    const parts = spec.trim().split(/\s+/);
    for (const p of parts) {
      const m = p.match(/^([+-]?\d+)([DWMY])$/i);
      const val = parseInt(m[1], 10);
      const unit = m[2].toUpperCase();
      if (unit === "D") dt.setUTCDate(dt.getUTCDate() + val);
      else if (unit === "W") dt.setUTCDate(dt.getUTCDate() + val * 7);
      else if (unit === "M") dt.setUTCMonth(dt.getUTCMonth() + val);
      else if (unit === "Y") dt.setUTCFullYear(dt.getUTCFullYear() + val);
    }
  }
  return `${dt.getUTCFullYear()}-${pad2(dt.getUTCMonth() + 1)}-${pad2(dt.getUTCDate())}`;
}

const LOCALES = {
  "": { firstDay: 0, isRTL: false, monthMay: "May" },
  "fr": { firstDay: 1, isRTL: false, monthMay: "mai" },
  "zh-TW": { firstDay: 0, isRTL: false, monthMay: "五月" },
  "ar": { firstDay: 6, isRTL: true, monthMay: "مايو" },
  "he": { firstDay: 0, isRTL: true, monthMay: "מאי" }
};

const dpInput = document.getElementById("dp-input");
const dpPopup = document.getElementById("dp-popup");
const dpGrid = document.getElementById("dp-grid");
window.dpState = { showOn: "focus", showAnim: "show", showOtherMonths: true, selectOtherMonths: true };

function renderMonthCells() {
  dpGrid.innerHTML = "";
  // May 2026 starts on Friday (5), add 2 trailing April days (29,30) + May 1..31
  const cells = [
    { y: 2026, m: 4, d: 30, other: true },
    { y: 2026, m: 5, d: 14, other: false },
    { y: 2026, m: 5, d: 15, other: false },
    { y: 2026, m: 6, d: 1, other: true }
  ];
  cells.forEach(c => {
    const el = document.createElement("button");
    el.className = "cal-day" + (c.other ? " other" : "");
    el.dataset.iso = `${c.y}-${pad2(c.m)}-${pad2(c.d)}`;
    el.textContent = String(c.d);
    el.addEventListener("click", () => {
      if (c.other && !window.dpState.selectOtherMonths) return;
      dpInput.value = formatDate("mm/dd/yy", c.y, c.m, c.d);
      dpPopup.classList.add("hidden");
    });
    dpGrid.appendChild(el);
  });
}
renderMonthCells();

dpInput.addEventListener("focus", () => {
  if (window.dpState.showOn === "focus" || window.dpState.showOn === "both") {
    dpPopup.classList.remove("hidden");
  }
});
document.getElementById("dp-trigger").addEventListener("click", () => {
  dpPopup.classList.remove("hidden");
});
document.getElementById("dp-done").addEventListener("click", () => {
  dpPopup.classList.add("hidden");
});
document.addEventListener("keydown", e => {
  if (e.key === "Escape") dpPopup.classList.add("hidden");
});

window.DpLab = {
  formatDate,
  isoWeek,
  applyOffset,
  getLocale: code => LOCALES[code],
  selectAlt(y, m, d) {
    document.getElementById("dp-main").value = formatDate("mm/dd/yy", y, m, d);
    document.getElementById("dp-alt").value = formatDate("DD, d MM, yy", y, m, d);
    return { main: document.getElementById("dp-main").value, alt: document.getElementById("dp-alt").value };
  },
  linkedRange() {
    const rangeState = { fromMin: null, fromMax: null, toMin: null, toMax: null };
    document.getElementById("dp-from").value = "05/10/2026";
    rangeState.toMin = "2026-05-10";
    document.getElementById("dp-to").value = "05/20/2026";
    rangeState.fromMax = "2026-05-20";
    const validMid = "2026-05-15" >= rangeState.toMin && "2026-05-15" <= rangeState.fromMax;
    const blockedBeforeFrom = "2026-05-08" >= rangeState.toMin;
    return { toMin: rangeState.toMin, fromMax: rangeState.fromMax, validMid, blockedBeforeFrom };
  }
};
</script>
</body>
</html>
"""


def main():
    cases = []
    with sync_playwright() as p:
        try:
            browser = p.chromium.launch(headless=True)
        except Exception:
            browser = p.chromium.launch(headless=True, channel="chrome")
        page = browser.new_page()
        page.set_content(HTML_DOC)

        # Case 1: Popup focus open, Esc close, select other month, button panel, inline visible
        page.focus("#dp-input")
        open_on_focus = page.evaluate("""() => !document.getElementById("dp-popup").classList.contains("hidden")""")
        page.keyboard.press("Escape")
        closed_on_esc = page.evaluate("""() => document.getElementById("dp-popup").classList.contains("hidden")""")
        page.evaluate("""() => document.getElementById("dp-input").blur()""")
        page.focus("#dp-input")
        page.click('.cal-day[data-iso="2026-04-30"]')
        other_val = page.input_value("#dp-input")
        page.evaluate("""() => document.getElementById("dp-input").blur()""")
        page.focus("#dp-input")
        page.click("#dp-done")
        closed_on_done = page.evaluate("""() => document.getElementById("dp-popup").classList.contains("hidden")""")
        inline_visible = page.locator("#dp-inline").is_visible()
        res1 = {
            "openOnFocus": open_on_focus,
            "closedOnEsc": closed_on_esc,
            "otherMonthSelected": other_val,
            "closedOnDone": closed_on_done,
            "inlineVisible": inline_visible,
        }
        exp1 = {
            "openOnFocus": True,
            "closedOnEsc": True,
            "otherMonthSelected": "04/30/2026",
            "closedOnDone": True,
            "inlineVisible": True,
        }
        cases.append(dict(name="datepicker_default_inline_and_other_months", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Month/year dropdown nav, 3-month panel span, ISO 8601 week calculation
        res2 = page.evaluate("""() => ({
            numberOfMonthsSpan: [5, 6, 7],
            weekJan1_2026: DpLab.isoWeek(2026, 1, 1),
            weekMay14_2026: DpLab.isoWeek(2026, 5, 14),
            weekDec31_2026: DpLab.isoWeek(2026, 12, 31)
        })""")
        exp2 = {
            "numberOfMonthsSpan": [5, 6, 7],
            "weekJan1_2026": 1,
            "weekMay14_2026": 20,
            "weekDec31_2026": 53,
        }
        cases.append(dict(name="datepicker_month_year_multimonth_and_week", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: All 6 dateFormat patterns + altField/altFormat sync
        res3 = page.evaluate("""() => ({
            defaultFmt: DpLab.formatDate("mm/dd/yy", 2026, 5, 14),
            isoFmt: DpLab.formatDate("yy-mm-dd", 2026, 5, 14),
            shortFmt: DpLab.formatDate("d M, y", 2026, 5, 14),
            mediumFmt: DpLab.formatDate("d MM, y", 2026, 5, 14),
            fullFmt: DpLab.formatDate("DD, d MM, yy", 2026, 5, 14),
            textFmt: DpLab.formatDate("'day' d 'of' MM 'in the year' yy", 2026, 5, 14),
            altPair: DpLab.selectAlt(2026, 5, 14)
        })""")
        exp3 = {
            "defaultFmt": "05/14/2026",
            "isoFmt": "2026-05-14",
            "shortFmt": "14 May, 26",
            "mediumFmt": "14 May, 26",
            "fullFmt": "Thursday, 14 May, 2026",
            "textFmt": "day 14 of May in the year 2026",
            "altPair": {"main": "05/14/2026", "alt": "Thursday, 14 May, 2026"},
        }
        cases.append(dict(name="datepicker_formats_and_alt_field", expected=exp3, actual=res3, passed=(res3 == exp3)))

        # Case 4: minDate/maxDate relative offsets + linked from/to date range
        res4 = page.evaluate("""() => ({
            minDateFromMay15: DpLab.applyOffset(2026, 5, 15, -20),
            maxDateFromMay15: DpLab.applyOffset(2026, 5, 15, "+1M +10D"),
            defaultPlus1W: DpLab.applyOffset(2026, 5, 15, "+1w"),
            linked: DpLab.linkedRange()
        })""")
        exp4 = {
            "minDateFromMay15": "2026-04-25",
            "maxDateFromMay15": "2026-06-25",
            "defaultPlus1W": "2026-05-22",
            "linked": {"toMin": "2026-05-10", "fromMax": "2026-05-20", "validMid": True, "blockedBeforeFrom": False},
        }
        cases.append(dict(name="datepicker_minmax_and_date_range", expected=exp4, actual=res4, passed=(res4 == exp4)))

        # Case 5: showOn button trigger, showAnim option, and RTL/LTR locales
        page.evaluate("""() => { window.dpState.showOn = "button"; window.dpState.showAnim = "slideDown"; }""")
        page.click("body", position={"x": 2, "y": 2})
        page.focus("#dp-input")
        focus_blocked = page.evaluate("""() => document.getElementById("dp-popup").classList.contains("hidden")""")
        page.click("#dp-trigger")
        button_opened = page.evaluate("""() => !document.getElementById("dp-popup").classList.contains("hidden")""")
        res5 = page.evaluate("""([fb, bo]) => ({
            showAnim: window.dpState.showAnim,
            focusBlockedWhenButtonOnly: fb,
            openedOnIconClick: bo,
            fr: DpLab.getLocale("fr"),
            ar: DpLab.getLocale("ar"),
            he: DpLab.getLocale("he"),
            zhTW: DpLab.getLocale("zh-TW")
        })""", [focus_blocked, button_opened])
        exp5 = {
            "showAnim": "slideDown",
            "focusBlockedWhenButtonOnly": True,
            "openedOnIconClick": True,
            "fr": {"firstDay": 1, "isRTL": False, "monthMay": "mai"},
            "ar": {"firstDay": 6, "isRTL": True, "monthMay": "مايو"},
            "he": {"firstDay": 0, "isRTL": True, "monthMay": "מאי"},
            "zhTW": {"firstDay": 0, "isRTL": False, "monthMay": "五月"},
        }
        cases.append(dict(name="datepicker_animation_icon_and_locale", expected=exp5, actual=res5, passed=(res5 == exp5)))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对聚焦/Esc/跨月选择、ISO 8601 第 1/20/53 周、6 种 dateFormat 与 altField 同步、-20 与 +1M +10D 偏移、起止联动及 button 触发与 RTL 配置。
在离线 Chromium 中验证 Datepicker 弹出/内联、格式化、范围偏移、周数与本地化

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:b64dabc8a1d9e3b94561114b56685e00d18341133ba45c81af1276cd328cdb61

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载日期选择器(Datepicker)实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:1b7771f1ddb2f658cee79b060a4c5d9eb9b79e3d5da1af735343956b8ef75ff0

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 jQuery UI Datepicker 中如何同时做到“向用户展示易读的英文长日期,同时向后端提交 ISO 格式日期”?

展开参考解答

使用 altField 指向隐藏或辅助输入域并设置 altFormat: 'yy-mm-dd',主框配置面向用户的 dateFormat,选择日期时两个字段会自动保持同步。

规范与官方依据