导航

v2.1.0
表单

日历

按月显示可选的日期:可以选择一天、多天或一个日期范围,也可以并排显示两个月。

本页内容

日历按月显示可供选择的日期:可以选择一天、一个日期范围或多个日期,可以显示一个月,也可以并排显示两个月。它是由按钮组成的 ARIA 网格,样式表负责呈现所有状态,calendar 行为脚本负责生成日期、处理月份切换按钮和方向键。日历本身没有表面,可以放在卡片中,也可以放在弹出层中组成日期选择器。

日历

<div class="sheet p-md">  <div class="calendar">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />        </svg>      </button>      <h3 class="calendar-title" id="cal-title" aria-live="polite">        <button type="button" class="calendar-title-button" aria-description="Choose a month or a year"></button>      </h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />        </svg>      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="cal-title"></div>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-react/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-react/native/16/soft/chevron-right'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="sheet p-md">      <div className="calendar">        <div className="calendar-header">          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Previous month">            <ChevronLeftIcon className="icon" />          </button>          <h3 className="calendar-title" id="cal-title" aria-live="polite">            <button type="button" className="calendar-title-button" aria-description="Choose a month or a year"></button>          </h3>          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Next month">            <ChevronRightIcon className="icon" />          </button>        </div>        <div className="calendar-grid" role="grid" aria-labelledby="cal-title"></div>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import ChevronLeftIcon from '@master/icons-svelte/native/16/soft/chevron-left'  import ChevronRightIcon from '@master/icons-svelte/native/16/soft/chevron-right'</script><div class="sheet p-md" {@attach attach}>  <div class="calendar">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <ChevronLeftIcon class="icon" />      </button>      <h3 class="calendar-title" id="cal-title" aria-live="polite">        <button type="button" class="calendar-title-button" aria-description="Choose a month or a year"></button>      </h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <ChevronRightIcon class="icon" />      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="cal-title"></div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-vue/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-vue/native/16/soft/chevron-right'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="sheet p-md">    <div class="calendar">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <ChevronLeftIcon class="icon" />        </button>        <h3 class="calendar-title" id="cal-title" aria-live="polite">          <button type="button" class="calendar-title-button" aria-description="Choose a month or a year"></button>        </h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <ChevronRightIcon class="icon" />        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="cal-title"></div>    </div>  </div></template>
点击日期即可选中,用两个按钮切换月份,或将焦点移到某个日期上再按方向键。点击标题可跳转到其他月份或年份。

标记由标题区和空网格组成。行为脚本将月份名称写入 calendar-title,将星期名称和各周的日期写入 calendar-grid,初始显示今天所在的月份。没有脚本时,网格会保留标记中的内容。如果日历需要在脚本运行前就可读,可参照下方日期范围示例,在服务端渲染各周的日期,行为脚本挂载时会替换这些内容。

#月份和年份

上方日历的标题是一个按钮,即 calendar-title 中的 calendar-title-button。点击它,网格会变为当年的十二个月;再次点击,网格会显示该十年区间内的各个年份,区间前后各一年的年份以弱化的墨色显示。选择某一年会显示它的各个月份,选择某个月会显示它的日期,焦点落在同一天上。按 Escape 会回到原来的日期视图。

月份和年份都是同一网格中的 calendar-period 按钮,每行三个,与日期按钮使用相同的材质。网格保持六周月份的高度,因此日历不会跳动。标题始终表明网格所处的位置:November 2026、2026、2020 – 2029。在月份视图中,月份切换按钮按年翻页;在年份视图中,按十年翻页;按钮在这两种视图中的名称取自 labels 选项。在年份视图中,标题按钮处于禁用状态,因为十年已是最上一级。

没有按钮的标题仍是普通标题,日历始终停留在日期视图。这种跳转适用于只显示一个月的日历。

另一种做法是在标题区放置原生的月份和年份下拉选择框,但未被采用:在部分语言中,两个下拉选择框加上两个月份切换按钮无法放进七个 36px 的列宽;一百年的列表在下拉选择框中需要长时间滚动;而可自定义样式的下拉选择框列表尚未得到所有浏览器的支持。月份和年份网格使用日历自身的材质,并沿用读者正在使用的按键。

#状态

每种状态都由日期按钮上的属性或类名表示。行为脚本会设置这些属性和类名,手写标记或服务端渲染时也使用同一套属性和类名。

状态标记方式显示效果
今天aria-current="date"数字下方显示圆点
已选中aria-selected="true"用墨色填充,与选中的复选框相同
非本月日期calendar-day-outside数字使用弱化的墨色
不可选disabled数字使用禁用状态的墨色

跳转视图中的月份或年份带有同样的标记:今天所在的月份或年份带有 aria-current="date",包含已选日期的月份或年份带有 aria-selected="true",在 min 和 max 之间没有任何日期的带有 disabled。calendar-period-outside 标记该十年区间之前和之后各一年的年份。

日期按钮会像菜单中的条目一样立即响应指针操作。今天被选中时仍保留圆点,圆点与日期数字使用相同的墨色。

#日期范围

日期范围的起止日期用墨色填充,中间以胶囊标签色调的色带相连。起始日期使用 calendar-day-range-start,结束日期使用 calendar-day-range-end,中间的日期使用 calendar-day-range。范围内的所有日期都使用 aria-selected="true"。

此预览只包含标记,未挂载脚本。可在代码视图中查看行为脚本生成整月日历时使用的标记,其中包含一个日期范围、今天和两个不可选的日期。

日期范围

<div class="sheet p-md">  <div class="calendar">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />        </svg>      </button>      <h3 class="calendar-title" id="range-title" aria-live="polite">November 2026</h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />        </svg>      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="range-title">      <div class="calendar-week" role="row">        <span class="calendar-weekday" role="columnheader" aria-label="Sunday">Sun</span>        <span class="calendar-weekday" role="columnheader" aria-label="Monday">Mon</span>        <span class="calendar-weekday" role="columnheader" aria-label="Tuesday">Tue</span>        <span class="calendar-weekday" role="columnheader" aria-label="Wednesday">Wed</span>        <span class="calendar-weekday" role="columnheader" aria-label="Thursday">Thu</span>        <span class="calendar-weekday" role="columnheader" aria-label="Friday">Fri</span>        <span class="calendar-weekday" role="columnheader" aria-label="Saturday">Sat</span>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 1, 2026">          1        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 2, 2026">          2        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 3, 2026">          3        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 4, 2026">          4        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 5, 2026">          5        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 6, 2026" disabled>          6        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 7, 2026" disabled>          7        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 8, 2026">          8        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 9, 2026">          9        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 10, 2026">          10        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 11, 2026" aria-current="date">          11        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 12, 2026">          12        </button>        <button type="button" class="calendar-day calendar-day-range-start" role="gridcell" tabindex="0" aria-label="Friday, November 13, 2026" aria-selected="true">          13        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Saturday, November 14, 2026" aria-selected="true">          14        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Sunday, November 15, 2026" aria-selected="true">          15        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Monday, November 16, 2026" aria-selected="true">          16        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Tuesday, November 17, 2026" aria-selected="true">          17        </button>        <button type="button" class="calendar-day calendar-day-range-end" role="gridcell" tabindex="-1" aria-label="Wednesday, November 18, 2026" aria-selected="true">          18        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 19, 2026">          19        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 20, 2026">          20        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 21, 2026">          21        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 22, 2026">          22        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 23, 2026">          23        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 24, 2026">          24        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 25, 2026">          25        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 26, 2026">          26        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 27, 2026">          27        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 28, 2026">          28        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 29, 2026">          29        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 30, 2026">          30        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Tuesday, December 1, 2026">          1        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Wednesday, December 2, 2026">          2        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Thursday, December 3, 2026">          3        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Friday, December 4, 2026">          4        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Saturday, December 5, 2026">          5        </button>      </div>    </div>  </div></div>
import ChevronLeftIcon from '@master/icons-react/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-react/native/16/soft/chevron-right'<div className="sheet p-md">  <div className="calendar">    <div className="calendar-header">      <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <ChevronLeftIcon className="icon" />      </button>      <h3 className="calendar-title" id="range-title" aria-live="polite">November 2026</h3>      <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <ChevronRightIcon className="icon" />      </button>    </div>    <div className="calendar-grid" role="grid" aria-labelledby="range-title">      <div className="calendar-week" role="row">        <span className="calendar-weekday" role="columnheader" aria-label="Sunday">Sun</span>        <span className="calendar-weekday" role="columnheader" aria-label="Monday">Mon</span>        <span className="calendar-weekday" role="columnheader" aria-label="Tuesday">Tue</span>        <span className="calendar-weekday" role="columnheader" aria-label="Wednesday">Wed</span>        <span className="calendar-weekday" role="columnheader" aria-label="Thursday">Thu</span>        <span className="calendar-weekday" role="columnheader" aria-label="Friday">Fri</span>        <span className="calendar-weekday" role="columnheader" aria-label="Saturday">Sat</span>      </div>      <div className="calendar-week" role="row">        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Sunday, November 1, 2026">          1        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Monday, November 2, 2026">          2        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Tuesday, November 3, 2026">          3        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Wednesday, November 4, 2026">          4        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Thursday, November 5, 2026">          5        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Friday, November 6, 2026" disabled>          6        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Saturday, November 7, 2026" disabled>          7        </button>      </div>      <div className="calendar-week" role="row">        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Sunday, November 8, 2026">          8        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Monday, November 9, 2026">          9        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Tuesday, November 10, 2026">          10        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Wednesday, November 11, 2026" aria-current="date">          11        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Thursday, November 12, 2026">          12        </button>        <button type="button" className="calendar-day calendar-day-range-start" role="gridcell" tabIndex={0} aria-label="Friday, November 13, 2026" aria-selected="true">          13        </button>        <button type="button" className="calendar-day calendar-day-range" role="gridcell" tabIndex={-1} aria-label="Saturday, November 14, 2026" aria-selected="true">          14        </button>      </div>      <div className="calendar-week" role="row">        <button type="button" className="calendar-day calendar-day-range" role="gridcell" tabIndex={-1} aria-label="Sunday, November 15, 2026" aria-selected="true">          15        </button>        <button type="button" className="calendar-day calendar-day-range" role="gridcell" tabIndex={-1} aria-label="Monday, November 16, 2026" aria-selected="true">          16        </button>        <button type="button" className="calendar-day calendar-day-range" role="gridcell" tabIndex={-1} aria-label="Tuesday, November 17, 2026" aria-selected="true">          17        </button>        <button type="button" className="calendar-day calendar-day-range-end" role="gridcell" tabIndex={-1} aria-label="Wednesday, November 18, 2026" aria-selected="true">          18        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Thursday, November 19, 2026">          19        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Friday, November 20, 2026">          20        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Saturday, November 21, 2026">          21        </button>      </div>      <div className="calendar-week" role="row">        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Sunday, November 22, 2026">          22        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Monday, November 23, 2026">          23        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Tuesday, November 24, 2026">          24        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Wednesday, November 25, 2026">          25        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Thursday, November 26, 2026">          26        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Friday, November 27, 2026">          27        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Saturday, November 28, 2026">          28        </button>      </div>      <div className="calendar-week" role="row">        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Sunday, November 29, 2026">          29        </button>        <button type="button" className="calendar-day" role="gridcell" tabIndex={-1} aria-label="Monday, November 30, 2026">          30        </button>        <button type="button" className="calendar-day calendar-day-outside" role="gridcell" tabIndex={-1} aria-label="Tuesday, December 1, 2026">          1        </button>        <button type="button" className="calendar-day calendar-day-outside" role="gridcell" tabIndex={-1} aria-label="Wednesday, December 2, 2026">          2        </button>        <button type="button" className="calendar-day calendar-day-outside" role="gridcell" tabIndex={-1} aria-label="Thursday, December 3, 2026">          3        </button>        <button type="button" className="calendar-day calendar-day-outside" role="gridcell" tabIndex={-1} aria-label="Friday, December 4, 2026">          4        </button>        <button type="button" className="calendar-day calendar-day-outside" role="gridcell" tabIndex={-1} aria-label="Saturday, December 5, 2026">          5        </button>      </div>    </div>  </div></div>
<script>  import ChevronLeftIcon from '@master/icons-svelte/native/16/soft/chevron-left'  import ChevronRightIcon from '@master/icons-svelte/native/16/soft/chevron-right'</script><div class="sheet p-md">  <div class="calendar">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <ChevronLeftIcon class="icon" />      </button>      <h3 class="calendar-title" id="range-title" aria-live="polite">November 2026</h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <ChevronRightIcon class="icon" />      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="range-title">      <div class="calendar-week" role="row">        <span class="calendar-weekday" role="columnheader" aria-label="Sunday">Sun</span>        <span class="calendar-weekday" role="columnheader" aria-label="Monday">Mon</span>        <span class="calendar-weekday" role="columnheader" aria-label="Tuesday">Tue</span>        <span class="calendar-weekday" role="columnheader" aria-label="Wednesday">Wed</span>        <span class="calendar-weekday" role="columnheader" aria-label="Thursday">Thu</span>        <span class="calendar-weekday" role="columnheader" aria-label="Friday">Fri</span>        <span class="calendar-weekday" role="columnheader" aria-label="Saturday">Sat</span>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 1, 2026">          1        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 2, 2026">          2        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 3, 2026">          3        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 4, 2026">          4        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 5, 2026">          5        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 6, 2026" disabled>          6        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 7, 2026" disabled>          7        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 8, 2026">          8        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 9, 2026">          9        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 10, 2026">          10        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 11, 2026" aria-current="date">          11        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 12, 2026">          12        </button>        <button type="button" class="calendar-day calendar-day-range-start" role="gridcell" tabindex="0" aria-label="Friday, November 13, 2026" aria-selected="true">          13        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Saturday, November 14, 2026" aria-selected="true">          14        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Sunday, November 15, 2026" aria-selected="true">          15        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Monday, November 16, 2026" aria-selected="true">          16        </button>        <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Tuesday, November 17, 2026" aria-selected="true">          17        </button>        <button type="button" class="calendar-day calendar-day-range-end" role="gridcell" tabindex="-1" aria-label="Wednesday, November 18, 2026" aria-selected="true">          18        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 19, 2026">          19        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 20, 2026">          20        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 21, 2026">          21        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 22, 2026">          22        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 23, 2026">          23        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 24, 2026">          24        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 25, 2026">          25        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 26, 2026">          26        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 27, 2026">          27        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 28, 2026">          28        </button>      </div>      <div class="calendar-week" role="row">        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 29, 2026">          29        </button>        <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 30, 2026">          30        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Tuesday, December 1, 2026">          1        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Wednesday, December 2, 2026">          2        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Thursday, December 3, 2026">          3        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Friday, December 4, 2026">          4        </button>        <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Saturday, December 5, 2026">          5        </button>      </div>    </div>  </div></div>
<script setup>import ChevronLeftIcon from '@master/icons-vue/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-vue/native/16/soft/chevron-right'</script><template>  <div class="sheet p-md">    <div class="calendar">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <ChevronLeftIcon class="icon" />        </button>        <h3 class="calendar-title" id="range-title" aria-live="polite">November 2026</h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <ChevronRightIcon class="icon" />        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="range-title">        <div class="calendar-week" role="row">          <span class="calendar-weekday" role="columnheader" aria-label="Sunday">Sun</span>          <span class="calendar-weekday" role="columnheader" aria-label="Monday">Mon</span>          <span class="calendar-weekday" role="columnheader" aria-label="Tuesday">Tue</span>          <span class="calendar-weekday" role="columnheader" aria-label="Wednesday">Wed</span>          <span class="calendar-weekday" role="columnheader" aria-label="Thursday">Thu</span>          <span class="calendar-weekday" role="columnheader" aria-label="Friday">Fri</span>          <span class="calendar-weekday" role="columnheader" aria-label="Saturday">Sat</span>        </div>        <div class="calendar-week" role="row">          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 1, 2026">            1          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 2, 2026">            2          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 3, 2026">            3          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 4, 2026">            4          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 5, 2026">            5          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 6, 2026" disabled>            6          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 7, 2026" disabled>            7          </button>        </div>        <div class="calendar-week" role="row">          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 8, 2026">            8          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 9, 2026">            9          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 10, 2026">            10          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 11, 2026" aria-current="date">            11          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 12, 2026">            12          </button>          <button type="button" class="calendar-day calendar-day-range-start" role="gridcell" tabindex="0" aria-label="Friday, November 13, 2026" aria-selected="true">            13          </button>          <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Saturday, November 14, 2026" aria-selected="true">            14          </button>        </div>        <div class="calendar-week" role="row">          <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Sunday, November 15, 2026" aria-selected="true">            15          </button>          <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Monday, November 16, 2026" aria-selected="true">            16          </button>          <button type="button" class="calendar-day calendar-day-range" role="gridcell" tabindex="-1" aria-label="Tuesday, November 17, 2026" aria-selected="true">            17          </button>          <button type="button" class="calendar-day calendar-day-range-end" role="gridcell" tabindex="-1" aria-label="Wednesday, November 18, 2026" aria-selected="true">            18          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 19, 2026">            19          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 20, 2026">            20          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 21, 2026">            21          </button>        </div>        <div class="calendar-week" role="row">          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 22, 2026">            22          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 23, 2026">            23          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Tuesday, November 24, 2026">            24          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Wednesday, November 25, 2026">            25          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Thursday, November 26, 2026">            26          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Friday, November 27, 2026">            27          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Saturday, November 28, 2026">            28          </button>        </div>        <div class="calendar-week" role="row">          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Sunday, November 29, 2026">            29          </button>          <button type="button" class="calendar-day" role="gridcell" tabindex="-1" aria-label="Monday, November 30, 2026">            30          </button>          <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Tuesday, December 1, 2026">            1          </button>          <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Wednesday, December 2, 2026">            2          </button>          <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Thursday, December 3, 2026">            3          </button>          <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Friday, December 4, 2026">            4          </button>          <button type="button" class="calendar-day calendar-day-outside" role="gridcell" tabindex="-1" aria-label="Saturday, December 5, 2026">            5          </button>        </div>      </div>    </div>  </div></template>

色带通过以下方式呈现为一个整体:

  • 列之间没有间距,色带可以跨单元格连续延伸。行之间保留 2px 间距,每周各有一条独立的色带。
  • 日期范围跨周延续时,色带在一周结束处呈圆角。
  • 在范围的两端,色带覆盖单元格朝向范围内侧的半边,墨色填充的日期另占一层,叠在色带上方。这样,色带会在日期按钮的中心与其衔接,而不是在圆角边缘与其相接。

启用 range 选项后,行为脚本会处理范围选择。第一次点击确定起始日期,第二次点击确定结束日期,第三次点击开始新的选择。如果第二次点击的日期更早,脚本会按时间先后排列两个日期。

选择日期范围

<div class="sheet p-md">  <div class="calendar" id="stay">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />        </svg>      </button>      <h3 class="calendar-title" id="stay-title" aria-live="polite"></h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />        </svg>      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="stay-title"></div>  </div></div><script>addEventListener('DOMContentLoaded', function () {MasterUI.calendar(document.getElementById('stay'), { range: true, value: ['2026-11-13', '2026-11-18'] })})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-react/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-react/native/16/soft/chevron-right'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => {    const detach = [      attach(root.current!),      calendar(document.getElementById('stay')!, { range: true, value: ['2026-11-13', '2026-11-18'] }),    ]    return () => detach.forEach(stop => stop())  }, [])  return (    <div ref={root} className="sheet p-md">      <div className="calendar" id="stay">        <div className="calendar-header">          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Previous month">            <ChevronLeftIcon className="icon" />          </button>          <h3 className="calendar-title" id="stay-title" aria-live="polite"></h3>          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Next month">            <ChevronRightIcon className="icon" />          </button>        </div>        <div className="calendar-grid" role="grid" aria-labelledby="stay-title"></div>      </div>    </div>  )}
<script>  import { attach, calendar } from '@master/ui/behaviors'  import ChevronLeftIcon from '@master/icons-svelte/native/16/soft/chevron-left'  import ChevronRightIcon from '@master/icons-svelte/native/16/soft/chevron-right'  function mounted(root) {    const detach = [      attach(root),      calendar(document.getElementById('stay'), { range: true, value: ['2026-11-13', '2026-11-18'] }),    ]    return () => detach.forEach(stop => stop())  }</script><div class="sheet p-md" {@attach mounted}>  <div class="calendar" id="stay">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <ChevronLeftIcon class="icon" />      </button>      <h3 class="calendar-title" id="stay-title" aria-live="polite"></h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <ChevronRightIcon class="icon" />      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="stay-title"></div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-vue/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-vue/native/16/soft/chevron-right'const root = ref(null)let detach = []onMounted(() => {  detach = [    attach(root.value),    calendar(document.getElementById('stay'), { range: true, value: ['2026-11-13', '2026-11-18'] }),  ]})onUnmounted(() => detach.forEach(stop => stop()))</script><template>  <div ref="root" class="sheet p-md">    <div class="calendar" id="stay">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <ChevronLeftIcon class="icon" />        </button>        <h3 class="calendar-title" id="stay-title" aria-live="polite"></h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <ChevronRightIcon class="icon" />        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="stay-title"></div>    </div>  </div></template>
点击一个日期作为起点,再点击另一个日期作为终点。

attach() 不传入选项,因此此预览会在 attach() 运行后自行调用 calendar。在同一根元素上再次调用会替换上一次挂载的行为。MasterUI 是预览加载的打包文件。在项目中,请按照行为脚本一节的示例导入 calendar。

#多个日期

启用 multiple 选项后,可以逐个选择任意数量的日期。点击、按 Enter 或 Space 会选中或取消选中某个日期,每个选中的日期都带有 aria-selected="true",网格带有 aria-multiselectable="true"。值是按先后排序、以 YYYY-MM-DD 表示的已选日期列表,每次变化都会派发全部已选日期。

多个日期

<div class="sheet p-md">  <div class="calendar" id="shifts">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />        </svg>      </button>      <h3 class="calendar-title" id="shifts-title" aria-live="polite"></h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />        </svg>      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="shifts-title"></div>  </div></div><script>addEventListener('DOMContentLoaded', function () {MasterUI.calendar(document.getElementById('shifts'), {  multiple: true,  value: ['2026-11-09', '2026-11-12', '2026-11-20'],  disabled: function (date) { return date.getDay() === 0 || date.getDay() === 6 }})})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-react/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-react/native/16/soft/chevron-right'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => {    const detach = [      attach(root.current!),      calendar(document.getElementById('shifts')!, {        multiple: true,        value: ['2026-11-09', '2026-11-12', '2026-11-20'],        disabled: function (date) { return date.getDay() === 0 || date.getDay() === 6 }      }),    ]    return () => detach.forEach(stop => stop())  }, [])  return (    <div ref={root} className="sheet p-md">      <div className="calendar" id="shifts">        <div className="calendar-header">          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Previous month">            <ChevronLeftIcon className="icon" />          </button>          <h3 className="calendar-title" id="shifts-title" aria-live="polite"></h3>          <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Next month">            <ChevronRightIcon className="icon" />          </button>        </div>        <div className="calendar-grid" role="grid" aria-labelledby="shifts-title"></div>      </div>    </div>  )}
<script>  import { attach, calendar } from '@master/ui/behaviors'  import ChevronLeftIcon from '@master/icons-svelte/native/16/soft/chevron-left'  import ChevronRightIcon from '@master/icons-svelte/native/16/soft/chevron-right'  function mounted(root) {    const detach = [      attach(root),      calendar(document.getElementById('shifts'), {        multiple: true,        value: ['2026-11-09', '2026-11-12', '2026-11-20'],        disabled: function (date) { return date.getDay() === 0 || date.getDay() === 6 }      }),    ]    return () => detach.forEach(stop => stop())  }</script><div class="sheet p-md" {@attach mounted}>  <div class="calendar" id="shifts">    <div class="calendar-header">      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">        <ChevronLeftIcon class="icon" />      </button>      <h3 class="calendar-title" id="shifts-title" aria-live="polite"></h3>      <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">        <ChevronRightIcon class="icon" />      </button>    </div>    <div class="calendar-grid" role="grid" aria-labelledby="shifts-title"></div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-vue/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-vue/native/16/soft/chevron-right'const root = ref(null)let detach = []onMounted(() => {  detach = [    attach(root.value),    calendar(document.getElementById('shifts'), {      multiple: true,      value: ['2026-11-09', '2026-11-12', '2026-11-20'],      disabled: function (date) { return date.getDay() === 0 || date.getDay() === 6 }    }),  ]})onUnmounted(() => detach.forEach(stop => stop()))</script><template>  <div ref="root" class="sheet p-md">    <div class="calendar" id="shifts">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <ChevronLeftIcon class="icon" />        </button>        <h3 class="calendar-title" id="shifts-title" aria-live="polite"></h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <ChevronRightIcon class="icon" />        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="shifts-title"></div>    </div>  </div></template>
点击工作日即可选中或取消选中。周末不可选。

min、max 和 disabled 的作用与选择单个日期时相同。同时启用 range 时,以 range 为准。

#多个月份

并排显示两个月,可以呈现跨越两个月的日期范围。每个月都是一个 calendar-month,各有自己的标题区和网格:第一个标题区放置切换到上个月的按钮,最后一个标题区放置切换到下个月的按钮,每个标题都位于对应网格上方。行为脚本按顺序填充各月,切换按钮让它们一起翻页,每次一个月。

两个月

<div class="sheet p-md">  <div class="calendar" id="trip">    <div class="calendar-month">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">            <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />          </svg>        </button>        <h3 class="calendar-title" id="trip-first" aria-live="polite"></h3>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="trip-first"></div>    </div>    <div class="calendar-month">      <div class="calendar-header">        <h3 class="calendar-title" id="trip-second" aria-live="polite"></h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">            <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />          </svg>        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="trip-second"></div>    </div>  </div></div><script>addEventListener('DOMContentLoaded', function () {MasterUI.calendar(document.getElementById('trip'), { range: true, value: ['2026-11-26', '2026-12-04'] })})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-react/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-react/native/16/soft/chevron-right'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => {    const detach = [      attach(root.current!),      calendar(document.getElementById('trip')!, { range: true, value: ['2026-11-26', '2026-12-04'] }),    ]    return () => detach.forEach(stop => stop())  }, [])  return (    <div ref={root} className="sheet p-md">      <div className="calendar" id="trip">        <div className="calendar-month">          <div className="calendar-header">            <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Previous month">              <ChevronLeftIcon className="icon" />            </button>            <h3 className="calendar-title" id="trip-first" aria-live="polite"></h3>          </div>          <div className="calendar-grid" role="grid" aria-labelledby="trip-first"></div>        </div>        <div className="calendar-month">          <div className="calendar-header">            <h3 className="calendar-title" id="trip-second" aria-live="polite"></h3>            <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label="Next month">              <ChevronRightIcon className="icon" />            </button>          </div>          <div className="calendar-grid" role="grid" aria-labelledby="trip-second"></div>        </div>      </div>    </div>  )}
<script>  import { attach, calendar } from '@master/ui/behaviors'  import ChevronLeftIcon from '@master/icons-svelte/native/16/soft/chevron-left'  import ChevronRightIcon from '@master/icons-svelte/native/16/soft/chevron-right'  function mounted(root) {    const detach = [      attach(root),      calendar(document.getElementById('trip'), { range: true, value: ['2026-11-26', '2026-12-04'] }),    ]    return () => detach.forEach(stop => stop())  }</script><div class="sheet p-md" {@attach mounted}>  <div class="calendar" id="trip">    <div class="calendar-month">      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">          <ChevronLeftIcon class="icon" />        </button>        <h3 class="calendar-title" id="trip-first" aria-live="polite"></h3>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="trip-first"></div>    </div>    <div class="calendar-month">      <div class="calendar-header">        <h3 class="calendar-title" id="trip-second" aria-live="polite"></h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">          <ChevronRightIcon class="icon" />        </button>      </div>      <div class="calendar-grid" role="grid" aria-labelledby="trip-second"></div>    </div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach, calendar } from '@master/ui/behaviors'import ChevronLeftIcon from '@master/icons-vue/native/16/soft/chevron-left'import ChevronRightIcon from '@master/icons-vue/native/16/soft/chevron-right'const root = ref(null)let detach = []onMounted(() => {  detach = [    attach(root.value),    calendar(document.getElementById('trip'), { range: true, value: ['2026-11-26', '2026-12-04'] }),  ]})onUnmounted(() => detach.forEach(stop => stop()))</script><template>  <div ref="root" class="sheet p-md">    <div class="calendar" id="trip">      <div class="calendar-month">        <div class="calendar-header">          <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">            <ChevronLeftIcon class="icon" />          </button>          <h3 class="calendar-title" id="trip-first" aria-live="polite"></h3>        </div>        <div class="calendar-grid" role="grid" aria-labelledby="trip-first"></div>      </div>      <div class="calendar-month">        <div class="calendar-header">          <h3 class="calendar-title" id="trip-second" aria-live="polite"></h3>          <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">            <ChevronRightIcon class="icon" />          </button>        </div>        <div class="calendar-grid" role="grid" aria-labelledby="trip-second"></div>      </div>    </div>  </div></template>
在两个月之间选择一个日期范围,或用方向键从一个月移到下一个月。

这些月份共用一个 Tab 键停靠点和同一套按键流程:在第一个月的最后一天按方向键会移到第二个月的第一天,移出最后一个月时两个月会一起翻页。非本月的日期留空,因为相邻的月份会显示这一天;留空的单元格保持星期列对齐。一行放不下时,各月会换行排成一列。

#日期选择器

日期选择器由输入字段、按钮和放在弹出层中的日历组成。弹出层无需脚本即可开关,并以按钮为参照自动定位。行为脚本生成日历并报告选中的日期,页面自己的脚本将该日期写入输入字段并隐藏弹出层。

日期选择器

<div class="field max-w(280) mx-auto">  <label for="starts">Starts</label>  <div class="input-group">    <input class="input-group-field" id="starts" value="2026-11-04" readonly>    <button type="button" class="btn btn-quiet btn-square" popovertarget="starts-calendar" aria-label="Choose a date">      <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">        <rect x="2.5" y="3.5" width="11" height="10.5" rx="1" /><path d="M2.5 6.5L13.5 6.5" /><path d="M5.5 2L5.5 4.5" /><path d="M10.5 2L10.5 4.5" /><circle cx="6" cy="9.5" r="0.5" fill="currentColor" stroke="none" /><circle cx="10" cy="9.5" r="0.5" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="0.5" fill="currentColor" stroke="none" />      </svg>    </button>    <div id="starts-calendar" popover class="popover popover-end">      <div class="calendar">        <div class="calendar-header">          <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Previous month">            <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">              <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" />            </svg>          </button>          <h3 class="calendar-title" id="picker-title" aria-live="polite"></h3>          <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Next month">            <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">              <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" />            </svg>          </button>        </div>        <div class="calendar-grid" role="grid" aria-labelledby="picker-title"></div>      </div>    </div>  </div></div><script>addEventListener('DOMContentLoaded', function () {var popover = document.getElementById('starts-calendar')MasterUI.calendar(popover.querySelector('.calendar'), { value: '2026-11-04' })popover.addEventListener('change', function (event) {  document.getElementById('starts').value = event.detail.value  popover.hidePopover()})})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>

日历的 change 事件会冒泡,因此监听器绑定在弹出层上。事件的 detail.value 提供 YYYY-MM-DD 格式的日期,这也是表单所需的日期值格式。

在手机上,或表单只需填写日期时,可以使用原生 <input type="date">,让用户使用设备自带的日期选择器。

#行为脚本

calendar 接收根元素和选项对象,并返回用于解除挂载的函数。

app.js
import { calendar } from '@master/ui/behaviors/calendar.js'const root = document.querySelector('.calendar')const picker = calendar(root, { value: '2026-11-04', min: '2026-11-01', max: '2026-12-31' })root.addEventListener('change', (event) => console.log(event.detail.value))
选项设置内容
valueYYYY-MM-DD 格式的选中日期、日期范围的起止日期,或通过 multiple 选中的各个日期
month初始显示的月份,格式为 YYYY-MM。默认显示所选值所在的月份,未设置值时显示今天所在的月份
min, max可选的最早和最晚日期,格式为 YYYY-MM-DD。某个方向没有可切换的月份时,对应的月份切换按钮会禁用
range用 true 选择两个日期及其间的所有日期
multiple设为 true 可逐个选择任意数量的日期;与 range 同时启用时以 range 为准
labels月份视图和年份视图中月份切换按钮的名称:previousYear、nextYear、previousDecade、nextDecade。默认为英文
weekStart第一列对应的星期几,0 表示星期日,6 表示星期六。默认遵循区域设置,浏览器无法确定时使用星期一
locale用于显示月份和星期名称的 BCP 47 标签。默认取日历所在范围的 lang
disabled接收 Date 并判断该日期是否不可选的函数
draw代替脚本生成各网格的函数。调用时传入以 YYYY-MM 表示的要显示的月份,以及视图:days、months 或 years。在日期视图中,它写入该月份,并在后续网格中写入之后的各月,每个月份由 calendarMonth(month, { offset }) 提供。在月份或年份视图中,它写入 calendarPeriods(month, { view }) 提供的单元格。参见自定义网格
  • 脚本写入的内容。 脚本写入星期名称、所显示的每个月的各周以及各月名称;在跳转视图中,写入月份或年份以及对应的标题。对日期按钮,脚本将日期写入 value,给今天加上 aria-current="date",给选中的日期加上 aria-selected="true" 和范围类名,给不可选的日期加上 disabled,用 aria-label 提供完整日期,并通过 tabindex 让一个日期进入 Tab 键导航顺序。使用 draw 时,由模板或框架生成日期,脚本只为这些日期添加标记。
  • 事件。 选择日期时,根元素会先派发 input,再派发 change。两个事件都会冒泡,并通过 detail.value 携带所选值。单个日期以 YYYY-MM-DD 表示,选定范围的两端后以 [start, end] 表示,启用 multiple 时则为排序后的日期列表。选定范围的第一端时只派发 input,值为 [start, null]:值已经改变,但要等选定第二端后才算完整。跳转到月份或年份视图时不会派发事件。
  • 值。 值保存在脚本中,不写入标记。通过返回函数的 value 读取,例如 picker.value。选择范围时,终点选定前为 null;启用 multiple 时,未选任何日期则为 []。也可以从外部设置这个值来选择日期。picker.value = '2026-11-20' 会显示新日期所在的月份,且不会派发事件。
  • 日期。 日期采用本地时区和公历。

#结构

  • calendar-grid 统一声明七列。每个 calendar-week 占一行,并使用这七列的子网格,因此无需表格即可让星期名称和日期按列对齐。
  • calendar-weekday 是列标题,其 aria-label 为完整的星期名称。
  • calendar-day 是带有 role="gridcell" 的 <button>。
  • calendar-title-button 在标题带有按钮时出现,是 calendar-title 中的 <button>,行为脚本将标题写入其中。
  • calendar-period 是跳转视图中的月份或年份:带有 role="gridcell" 的 <button>,值为 YYYY-MM 或 YYYY,每个 calendar-week 中放三个。
  • calendar-month 在显示多个月时容纳其中一个月的标题区和网格。

#键盘操作

行为脚本为网格提供日期网格的键盘操作。焦点移出当前月份时,日历会显示相邻月份,并将焦点保持在移到的日期上。移动时会跳过不可选的日期,并在 min 和 max 处停止。在月份和年份视图中,方向键每次移动一格或一行(三格),按 Enter 选择后回到下一级视图。

按键操作
ArrowLeft, ArrowRight将焦点移到前一天或后一天,在从右到左的布局中方向相反。从一个月的最后一天移到下个月的第一天;显示多个月时,移入相邻的网格。显示月份或年份时,移到前一项或后一项
ArrowUp, ArrowDown将焦点移到上一周或下一周的同一星期几。显示月份或年份时,移到上一行或下一行中前后相隔三项的位置
Home, End将焦点移到一周的第一天或最后一天;显示月份或年份时,移到该行的第一项或最后一项
PageUp, PageDown切换到上个月或下个月,并将焦点移到同一日。若该月没有对应日期,则移到该月最后一天。显示月份或年份时,切换到上一年或下一年,或上一个或下一个十年
Shift+PageUp, Shift+PageDown切换到上一年或下一年的同月,并将焦点移到同一日
Enter, Space选择当前聚焦的日期;使用 multiple 时切换其选中状态。焦点在月份或年份上时,显示该月的日期或该年的月份。单元格是 button,浏览器会将按键转为对它的点击
Escape显示月份或年份时,返回日期视图,焦点回到原先的日期。显示日期时,交由包含日历的元素处理,例如 popover
Tab进入网格时优先聚焦已选日期(有多个时聚焦第一个),其次聚焦今天。若显示的月份中两者皆无,则聚焦其中第一天。多个月的网格合起来在 Tab 顺序中只占一项

#无障碍

  • 网格为 role="grid",以月份标题作为无障碍名称。每周为 role="row"。
  • Tab 键导航顺序中只有一个日期,优先使用选中的日期(选中多个时取第一个),其次使用今天。如果所显示的月份两者都没有,则使用这些月份的第一天。其余日期均带有 tabindex="-1"。并排显示的多个月份共用一个 Tab 键停靠点,每个网格以各自的标题作为无障碍名称。
  • 可以选择日期范围或多个日期的网格带有 aria-multiselectable="true"。
  • 标题按钮以其显示的标题命名,该标题同时也是网格的无障碍名称。请用 aria-description 说明按钮的作用,例如“选择月份或年份”,而不要用 aria-label,否则网格的名称也会随之改变。
  • 为标题添加 aria-live="polite",以便在切换月份时播报。
  • 在触摸屏上,日期按钮保持 36px:网格仍保持一个月的形状,而且日期按钮本身已大于手指所需的尺寸。
  • 在日历旁说明日期的含义:例如用“周末不营业”说明哪些日期不可选的原因;选择范围时,说明两端分别代表什么,例如入住日和退房日。禁用的日期或墨色的端点都无法传达这些信息。

#React、Svelte 和 Vue

calendar 组件使用与行为脚本相同的数据渲染月份,使月份内容出现在初始 HTML 中,并支持传入和传出所选日期。启用 range 时,值会传出两次:选定第一端时为 [start, null],选定第二端时为 [start, end]。它接受 range 和 multiple,用 months 并排显示多个月,只显示一个月时带有标题按钮;jumpLabel 是该按钮的描述,labels 是月份视图和年份视图中月份切换按钮的名称。使用 npx master-ui add calendar 将组件复制到项目中,参见 React、Svelte 和 Vue 了解这些组件的实现和用法。

ui/calendar.tsx
'use client'import { Fragment, useId, useMemo, useState, type ComponentProps } from 'react'import { calendar, calendarMonth, calendarPeriods, type CalendarLabels, type CalendarView } from '@master/ui/behaviors/calendar.js'import { useBehavior } from './use-behavior'/** A day as `YYYY-MM-DD`; in a range, its two ends, the second null until it is chosen; with `multiple`, the days chosen, sorted. */export type CalendarValue = string | [string, string | null] | string[] | nullexport interface CalendarProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'children' | 'ref'> {  value?: CalendarValue  defaultValue?: CalendarValue  onValueChange?: (value: CalendarValue) => void  /** Choose two days and every day between them. */  range?: boolean  /** Choose any number of separate days; the value is their list. `range` wins over it. */  multiple?: boolean  /** How many months to show side by side, 1 by default. A calendar of one month has a title that jumps to the months and the years. */  months?: number  /** The first and the last day that can be chosen, as `YYYY-MM-DD`. */  min?: string  max?: string  /** The month to show first, as `YYYY-MM`. The month of the value, or this month, by default. */  month?: string  /** The day in the first column, 0 for Sunday to 6 for Saturday. The locale's own by default. */  weekStart?: number  /** A BCP 47 tag for the names. Give it when the calendar is rendered on a server, so both sides agree. */  locale?: string  /** Says whether a day cannot be chosen. */  disabled?: (date: Date) => boolean  previousLabel?: string  nextLabel?: string  /** What the title button does, said to assistive technology. */  jumpLabel?: string  /** The names of the month buttons while the grid shows months or years. */  labels?: CalendarLabels}/** * A calendar. React writes the months, from the same data the behavior uses, so they are in the first HTML; * the behavior marks today, the chosen days and the day in the tab order, and asks for other months, or for * the months of a year or the years of a decade when the title jumps. */export function Calendar({ value, defaultValue, onValueChange, range, multiple, months = 1, min, max, month, weekStart, locale, disabled, previousLabel = 'Previous month', nextLabel = 'Next month', jumpLabel = 'Choose a month or a year', labels, className, ...root }: CalendarProps) {  const id = useId()  const [first] = useState(value ?? defaultValue)  const [shown, setShown] = useState(() => calendarMonth(month, { value: first }).month)  const [view, setView] = useState<CalendarView>('days')  const count = Math.max(1, Math.floor(months))  // The first value's days are marked in the first render; after that the behavior marks what is chosen.  const grids = useMemo(() => Array.from({ length: count }, (_, offset) => calendarMonth(shown, { weekStart, locale, value: first, range, multiple, offset })), [count, shown, weekStart, locale, first, range, multiple])  const periods = view === 'days' ? null : calendarPeriods(shown, { view, locale })  const ref = useBehavior(calendar, {    value: (first ?? undefined) as string | string[] | undefined,    range,    multiple,    min,    max,    month,    weekStart,    locale,    disabled,    labels,    draw: (next: string, nextView: CalendarView) => { setShown(next); setView(nextView) },  }, { value, onValueChange })  const several = range || multiple || undefined  const previous = (    <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label={previousLabel}>      <svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" /></svg>    </button>  )  const next = (    <button type="button" className="btn btn-quiet btn-square btn-sm" aria-label={nextLabel}>      <svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" /></svg>    </button>  )  return (    <div className={className ? `calendar ${className}` : 'calendar'} ref={ref} {...root}>      {grids.map((data, index) => {        const one = count === 1        const title = `${id}title${index}`        const header = (          <div className="calendar-header">            {index === 0 && previous}            <h3 className="calendar-title" id={title} aria-live="polite">              {one ? <button type="button" className="calendar-title-button" aria-description={jumpLabel}>{periods?.title ?? data.title}</button> : data.title}            </h3>            {index === count - 1 && next}          </div>        )        const grid = (          <div className="calendar-grid" role="grid" aria-labelledby={title} aria-multiselectable={several}>            {one && periods              ? periods.rows.map(row => (                  <div className="calendar-week" role="row" key={row[0]!.value}>                    {row.map(cell => <button type="button" className={cell.outside ? 'calendar-period calendar-period-outside' : 'calendar-period'} role="gridcell" tabIndex={-1} value={cell.value} aria-label={cell.label} key={cell.value}>{cell.text}</button>)}                  </div>                ))              : (                  <>                    <div className="calendar-week" role="row">                      {data.weekdays.map(weekday => <span className="calendar-weekday" role="columnheader" aria-label={weekday.name} key={weekday.name}>{weekday.short}</span>)}                    </div>                    {data.weeks.map(week => (                      <div className="calendar-week" role="row" key={week[0]!.date}>                        {week.map(day => <button type="button" className={['calendar-day', day.outside && 'calendar-day-outside', day.range].filter(Boolean).join(' ')} role="gridcell" tabIndex={day.tab ? 0 : -1} value={day.date} aria-selected={day.selected || undefined} aria-label={day.label} key={day.date}>{day.text}</button>)}                      </div>                    ))}                  </>                )}          </div>        )        // One month is a header and a grid. Each of several is a calendar-month, which keeps its place, so the        // button in its header keeps focus while the months turn.        return one ? <Fragment key={index}>{header}{grid}</Fragment> : <div className="calendar-month" key={index}>{header}{grid}</div>      })}    </div>  )}
ui/Calendar.svelte
<script lang="ts" module>  import type { HTMLAttributes } from 'svelte/elements'  import type { CalendarLabels } from '@master/ui/behaviors/calendar.js'  /** A day as `YYYY-MM-DD`; in a range, its two ends, the second null until it is chosen; with `multiple`, the days chosen, sorted. */  export type CalendarValue = string | [string, string | null] | string[] | null  export interface CalendarProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {    /** What is chosen. Bind it, or leave it out and the pattern keeps its own. */    value?: CalendarValue    onValueChange?: (value: CalendarValue) => void    /** Choose two days and every day between them. */    range?: boolean    /** Choose any number of separate days; the value is their list. `range` wins over it. */    multiple?: boolean    /** How many months to show side by side, 1 by default. A calendar of one month has a title that jumps to the months and the years. */    months?: number    /** The first and the last day that can be chosen, as `YYYY-MM-DD`. */    min?: string    max?: string    /** The month to show first, as `YYYY-MM`. The month of the value, or this month, by default. */    month?: string    /** The day in the first column, 0 for Sunday to 6 for Saturday. The locale's own by default. */    weekStart?: number    /** A BCP 47 tag for the names. Give it when the calendar is rendered on a server, so both sides agree. */    locale?: string    /** Says whether a day cannot be chosen. */    disabled?: (date: Date) => boolean    previousLabel?: string    nextLabel?: string    /** What the title button does, said to assistive technology. */    jumpLabel?: string    /** The names of the month buttons while the grid shows months or years. */    labels?: CalendarLabels  }</script><script lang="ts">  import { untrack } from 'svelte'  import { calendar, calendarMonth, calendarPeriods, type CalendarMonth, type CalendarView } from '@master/ui/behaviors/calendar.js'  import { behavior } from './behavior.svelte.js'  let { value = $bindable(), onValueChange, range, multiple, months = 1, min, max, month, weekStart, locale, disabled, previousLabel = 'Previous month', nextLabel = 'Next month', jumpLabel = 'Choose a month or a year', labels, class: className, ...root }: CalendarProps = $props()  const id = $props.id()  const first = untrack(() => value)  let shown = $state(untrack(() => calendarMonth(month, { value: first }).month))  let view = $state<CalendarView>('days')  const count = $derived(Math.max(1, Math.floor(months)))  // The first value's days are marked in the first render; after that the behavior marks what is chosen.  const grids = $derived(Array.from({ length: count }, (_, offset) => calendarMonth(shown, { weekStart, locale, value: first, range, multiple, offset })))  const periods = $derived(view === 'days' ? null : calendarPeriods(shown, { view, locale }))  const several = $derived(range || multiple || undefined)  const attach = behavior(calendar, () => ({    value: (first ?? undefined) as string | string[] | undefined,    range,    multiple,    min,    max,    month,    weekStart,    locale,    disabled,    labels,    draw: (next: string, nextView: CalendarView) => { shown = next; view = nextView },  }), {    value: () => value,    change: (next) => { value = next; onValueChange?.(next) },  })</script><!--  @component  A calendar. Svelte writes the months, from the same data the behavior uses, so they are in the first HTML;  the behavior marks today, the chosen days and the day in the tab order, and asks for other months, or for  the months of a year or the years of a decade when the title jumps.-->{#snippet previous()}  <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label={previousLabel}>    <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" /></svg>  </button>{/snippet}{#snippet next()}  <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label={nextLabel}>    <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" /></svg>  </button>{/snippet}{#snippet days(data: CalendarMonth)}  <div class="calendar-week" role="row">    {#each data.weekdays as weekday (weekday.name)}      <span class="calendar-weekday" role="columnheader" aria-label={weekday.name}>{weekday.short}</span>    {/each}  </div>  {#each data.weeks as week (week[0]!.date)}    <div class="calendar-week" role="row">      {#each week as day (day.date)}        <button type="button" class={['calendar-day', day.outside && 'calendar-day-outside', day.range]} role="gridcell" tabindex={day.tab ? 0 : -1} value={day.date} aria-selected={day.selected || undefined} aria-label={day.label}>{day.text}</button>      {/each}    </div>  {/each}{/snippet}<div class={['calendar', className]} {@attach attach} {...root}>  {#if count > 1}    <!-- A month keeps its place, so the button in its header keeps focus while the months turn. -->    {#each grids as data, index (index)}      <div class="calendar-month">        <div class="calendar-header">          {#if index === 0}{@render previous()}{/if}          <h3 class="calendar-title" id="{id}title{index}" aria-live="polite">{data.title}</h3>          {#if index === count - 1}{@render next()}{/if}        </div>        <div class="calendar-grid" role="grid" aria-labelledby="{id}title{index}" aria-multiselectable={several}>          {@render days(data)}        </div>      </div>    {/each}  {:else}    <div class="calendar-header">      {@render previous()}      <!-- aria-description is an ARIA 1.3 attribute of every role, which Svelte's element types do not know yet. -->      <h3 class="calendar-title" id="{id}title" aria-live="polite"><button type="button" class="calendar-title-button" {...{ 'aria-description': jumpLabel }}>{periods?.title ?? grids[0]!.title}</button></h3>      {@render next()}    </div>    <div class="calendar-grid" role="grid" aria-labelledby="{id}title" aria-multiselectable={several}>      {#if periods}        {#each periods.rows as row (row[0]!.value)}          <div class="calendar-week" role="row">            {#each row as cell (cell.value)}              <button type="button" class={cell.outside ? 'calendar-period calendar-period-outside' : 'calendar-period'} role="gridcell" tabindex={-1} value={cell.value} aria-label={cell.label}>{cell.text}</button>            {/each}          </div>        {/each}      {:else}        {@render days(grids[0]!)}      {/if}    </div>  {/if}</div>
ui/Calendar.vue
<script lang="ts">/** A day as `YYYY-MM-DD`; in a range, its two ends, the second null until it is chosen; with `multiple`, the days chosen, sorted. */export type CalendarValue = string | [string, string | null] | string[] | null</script><script setup lang="ts">import { computed, shallowRef, useId, useTemplateRef } from 'vue'import { calendar, calendarMonth, calendarPeriods, type CalendarLabels, type CalendarView } from '@master/ui/behaviors/calendar.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { range, multiple, months = 1, min, max, month, weekStart, locale, disabled, previousLabel = 'Previous month', nextLabel = 'Next month', jumpLabel = 'Choose a month or a year', labels } = defineProps<{  /** Choose two days and every day between them. */  range?: boolean  /** Choose any number of separate days; the value is their list. `range` wins over it. */  multiple?: boolean  /** How many months to show side by side, 1 by default. A calendar of one month has a title that jumps to the months and the years. */  months?: number  /** The first and the last day that can be chosen, as `YYYY-MM-DD`. */  min?: string  max?: string  /** The month to show first, as `YYYY-MM`. The month of the value, or this month, by default. */  month?: string  /** The day in the first column, 0 for Sunday to 6 for Saturday. The locale's own by default. */  weekStart?: number  /** A BCP 47 tag for the names. Give it when the calendar is rendered on a server, so both sides agree. */  locale?: string  /** Says whether a day cannot be chosen. */  disabled?: (date: Date) => boolean  previousLabel?: string  nextLabel?: string  /** What the title button does, said to assistive technology. */  jumpLabel?: string  /** The names of the month buttons while the grid shows months or years. */  labels?: CalendarLabels}>()/** The chosen day, the two ends of a range, or the days chosen with `multiple`: `v-model`. */const model = defineModel<CalendarValue>()/* * A calendar. Vue writes the months, from the same data the behavior uses, so they are in the first HTML; * the behavior marks today, the chosen days and the day in the tab order, and asks for other months, or for * the months of a year or the years of a decade when the title jumps. */const id = useId()const first = model.valueconst shown = shallowRef(calendarMonth(month, { value: first }).month)const view = shallowRef<CalendarView>('days')const count = computed(() => Math.max(1, Math.floor(months)))// The first value's days are marked in the first render; after that the behavior marks what is chosen.const grids = computed(() => Array.from({ length: count.value }, (_, offset) => calendarMonth(shown.value, { weekStart, locale, value: first, range, multiple, offset })))const periods = computed(() => (view.value === 'days' ? null : calendarPeriods(shown.value, { view: view.value, locale })))const several = computed(() => range || multiple || undefined)const root = useTemplateRef<HTMLDivElement>('root')useBehavior(root, calendar, () => ({  value: (first ?? undefined) as string | string[] | undefined,  range,  multiple,  min,  max,  month,  weekStart,  locale,  disabled,  labels,  draw: (next: string, nextView: CalendarView) => {    shown.value = next    view.value = nextView  },}), model)</script><template>  <div ref="root" class="calendar" v-bind="$attrs">    <template v-if="count > 1">      <div v-for="(data, index) in grids" :key="index" class="calendar-month">        <div class="calendar-header">          <button v-if="index === 0" type="button" class="btn btn-quiet btn-square btn-sm" :aria-label="previousLabel">            <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" /></svg>          </button>          <h3 :id="`${id}-title-${index}`" class="calendar-title" aria-live="polite">{{ data.title }}</h3>          <button v-if="index === count - 1" type="button" class="btn btn-quiet btn-square btn-sm" :aria-label="nextLabel">            <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" /></svg>          </button>        </div>        <div class="calendar-grid" role="grid" :aria-labelledby="`${id}-title-${index}`" :aria-multiselectable="several">          <div class="calendar-week" role="row">            <span v-for="weekday in data.weekdays" :key="weekday.name" class="calendar-weekday" role="columnheader" :aria-label="weekday.name">{{ weekday.short }}</span>          </div>          <div v-for="week in data.weeks" :key="week[0]!.date" class="calendar-week" role="row">            <button v-for="day in week" :key="day.date" type="button" class="calendar-day" :class="[{ 'calendar-day-outside': day.outside }, day.range]" role="gridcell" :tabindex="day.tab ? 0 : -1" :value="day.date" :aria-selected="day.selected || undefined" :aria-label="day.label">{{ day.text }}</button>          </div>        </div>      </div>    </template>    <template v-else>      <div class="calendar-header">        <button type="button" class="btn btn-quiet btn-square btn-sm" :aria-label="previousLabel">          <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(180 8 8)" /></svg>        </button>        <h3 :id="`${id}-title`" class="calendar-title" aria-live="polite"><button type="button" class="calendar-title-button" :aria-description="jumpLabel">{{ periods?.title ?? grids[0]!.title }}</button></h3>        <button type="button" class="btn btn-quiet btn-square btn-sm" :aria-label="nextLabel">          <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" /></svg>        </button>      </div>      <div class="calendar-grid" role="grid" :aria-labelledby="`${id}-title`" :aria-multiselectable="several">        <template v-if="periods">          <div v-for="row in periods.rows" :key="row[0]!.value" class="calendar-week" role="row">            <button v-for="cell in row" :key="cell.value" type="button" class="calendar-period" :class="{ 'calendar-period-outside': cell.outside }" role="gridcell" :tabindex="-1" :value="cell.value" :aria-label="cell.label">{{ cell.text }}</button>          </div>        </template>        <template v-else>          <div class="calendar-week" role="row">            <span v-for="weekday in grids[0]!.weekdays" :key="weekday.name" class="calendar-weekday" role="columnheader" :aria-label="weekday.name">{{ weekday.short }}</span>          </div>          <div v-for="week in grids[0]!.weeks" :key="week[0]!.date" class="calendar-week" role="row">            <button v-for="day in week" :key="day.date" type="button" class="calendar-day" :class="[{ 'calendar-day-outside': day.outside }, day.range]" role="gridcell" :tabindex="day.tab ? 0 : -1" :value="day.date" :aria-selected="day.selected || undefined" :aria-label="day.label">{{ day.text }}</button>          </div>        </template>      </div>    </template>  </div></template>

#类名

类名说明
calendar日历本体:日期网格上方是标题栏;并排显示多个月时,每个月使用一个 calendar-month
calendar-month并排显示的多个月中的一个月,各自包含 calendar-header 和 calendar-grid。不属于该月的日期留空,因为相邻的月份会显示它们;一行放不下时,各月换行排成一列
calendar-header网格上方的一行依次放置上个月按钮、标题和下个月按钮。显示多个月时,上个月按钮放在第一个月的标题栏中,下个月按钮放在最后一个月的标题栏中
calendar-title月份名称在两个按钮之间居中。设置 aria-live="polite",以便在切换月份时播报。其中可放入 calendar-title-button
calendar-title-button在只显示一个月的日历中,将标题做成按钮:点击后网格显示当年的十二个月,再点击则显示该十年中的各个年份,此时按钮变为禁用。行为脚本会将标题写入按钮
calendar-grid七列网格,设置 role="grid",并以标题作为标签。可选择日期范围或多个日期时,设置 aria-multiselectable="true"。显示月份或年份时,网格为三列
calendar-week沿网格列排列的一行,设置 role="row",用于显示星期名称、一周的日期,或三个月份或年份
calendar-weekday带 role="columnheader" 的列标题。将星期全称设为 aria-label。
calendar-day用带 role="gridcell" 的按钮表示日期。只有一个日期进入 Tab 顺序,其余日期设置 tabindex="-1"。值为 YYYY-MM-DD 格式的日期。行为脚本会写入该值,也会从其他来源生成的日期元素中读取它。
calendar-day-outside用于补齐一周的上月或下月日期,以较淡的墨色显示。与 calendar-day 一同使用
calendar-day-range-start日期范围的首日,日期以墨色显示,色带覆盖单元格朝向范围内侧的一半。同一天也使用 calendar-day-range-end 时,范围仅含这一天。与 calendar-day 一同使用
calendar-day-range日期范围内的中间日期,以胶囊标签色调的色带连接各单元格,并在每周末尾收成圆角。与 calendar-day 一同使用
calendar-day-range-end日期范围的末日,日期以墨色显示,色带覆盖单元格朝向范围内侧的一半。与 calendar-day 一同使用
calendar-period点击标题后网格中显示的月份或年份,使用带 role="gridcell" 的按钮,沿用日期的材质,四行的总高度与六周相同。月份的值为 YYYY-MM,年份的值为 YYYY
calendar-period-outside该十年之前或之后的年份,以弱化墨色显示,用于补齐各行与 calendar-period 一同使用

#自定义属性

属性默认值说明
--calendar-cell2.25rem日期单元格的宽度和高度,本身已大于手指所需的尺寸
--calendar-day-radiusvar(--radius-control-sm)日期单元格的圆角

#源码

@master/ui/components/calendar.css
/* * Calendar: a month of days to pick from, as an ARIA grid of buttons. * The stylesheet draws every state and leaves the dates and the keys to the script that fills it: today is * aria-current="date" and carries a dot, a chosen day is aria-selected and fills with ink the way a checkbox * does, and a range is a chip-toned band between two ink days. Weeks are rows on a subgrid, so the seven * columns are declared once. It has no surface of its own: put it in a popover for a date picker, or a card. * * The title may hold a button that jumps to the months of the year and the years of a decade: they are cells of * the same grid, three to a row, in the day's material, and the grid keeps the height of a six-week month so the * calendar does not jump with it. Several months side by side are a calendar-month each, wrapping to a column * where the row has no room; there the days outside a month are left blank, since the month beside it shows them. */@layer components.ui {  .calendar {    --calendar-cell: 2.25rem;    --calendar-day-radius: var(--radius-control-sm);    /* The width of a month button, which a title with a button on one side only keeps free on the other. */    --calendar-turn: 2rem;    display: inline-grid;    gap: .5rem;    min-width: 0;    color: var(--color-text-strong);    font: 400 .8125rem/1 var(--font-family-sans);    font-feature-settings: inherit;    font-variant-numeric: tabular-nums;    user-select: none;    -webkit-user-select: none;  }  /* Several months side by side: a column of them where the row has no room. */  .calendar:has(.calendar-month) {    display: inline-flex;    flex-wrap: wrap;    align-items: flex-start;    gap: 1rem 1.5rem;  }  /* One month of several: its header and its grid. */  .calendar-month {    display: grid;    gap: .5rem;    min-width: 0;    /* A day of the month before or after is shown by that month, so here it only keeps its column. */    & .calendar-day-outside {      visibility: hidden;    }  }  /* Previous, the month, next. */  .calendar-header {    display: flex;    align-items: center;    justify-content: space-between;    gap: .5rem;  }  .calendar-title {    flex: 1 1 0;    margin: 0;    color: var(--color-text-strong);    font: var(--font-weight-control) .875rem/1.4 var(--font-family-sans);    font-feature-settings: inherit;    text-align: center;    /* In a month of several the title may have a month button on one side only; it stays over the middle. */    &:first-child {      margin-inline-start: calc(var(--calendar-turn) + .5rem);    }    &:last-child {      margin-inline-end: calc(var(--calendar-turn) + .5rem);    }  }  /* The title as a button: it shows the months of the year, then the years of the decade. */  .calendar-title-button {    display: inline-flex;    align-items: center;    max-width: 100%;    min-height: 2rem;    margin: 0;    padding: 0 .5rem;    border: 0;    border-radius: calc(var(--calendar-day-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: transparent;    color: inherit;    font: inherit;    font-feature-settings: inherit;    appearance: none;    -webkit-tap-highlight-color: transparent;    cursor: pointer;    touch-action: manipulation;    /* Like a day, it answers at once. */    @media (hover: hover) {      &:hover:not(:disabled) {        background: var(--color-surface-chip);      }    }    &:active:not(:disabled) {      background: var(--color-surface-inset-hover);    }    &:focus-visible {      @apply --focus-ring;    }    /* At the decade there is nowhere further to go: it reads as the title it is. */    &:disabled {      cursor: default;    }    /* On touch the target reaches 44px around the title, which keeps its height. */    @media (pointer: coarse) {      position: relative;      &::after {        @apply --touch-target;      }    }  }  /* Seven columns; rows keep 2px apart so a range reads as one band per week. */  .calendar-grid {    display: grid;    grid-template-columns: repeat(7, var(--calendar-cell));    row-gap: 2px;    /* The months or the years: three columns over the same width. */    &:has(.calendar-period) {      grid-template-columns: repeat(3, 1fr);      width: calc(var(--calendar-cell) * 7);      gap: 4px;    }  }  /* A row of the grid: the weekday names, or a week of days, on the grid's own columns. */  .calendar-week {    display: grid;    grid-column: 1 / -1;    grid-template-columns: subgrid;  }  .calendar-weekday {    display: grid;    place-items: center;    height: 1.75rem;    color: var(--color-text-muted);    font-size: .71875rem;    font-weight: 400;  }  /* A day, or a month or a year: a button in a grid cell. */  .calendar-day, .calendar-period {    position: relative;    isolation: isolate;    display: grid;    place-items: center;    width: 100%;    height: var(--calendar-cell);    margin: 0;    padding: 0;    border: 0;    border-radius: calc(var(--calendar-day-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: transparent;    color: inherit;    font: inherit;    font-feature-settings: inherit;    appearance: none;    -webkit-tap-highlight-color: transparent;    cursor: pointer;    touch-action: manipulation;    font-variant-numeric: tabular-nums;    /* A day answers at once, like a row in a menu. */    @media (hover: hover) {      &:hover:not(:disabled, [aria-disabled="true"], [aria-selected="true"], [aria-pressed="true"]) {        background: var(--color-surface-chip);      }    }    /* Pressed: a step deeper than the pointer's tone. */    &:active:not(:disabled, [aria-disabled="true"], [aria-selected="true"], [aria-pressed="true"]) {      background: var(--color-surface-inset-hover);    }    /*     * Today keeps its place in the month with a dot under the number. It keeps the weight of every other day, so     * the number is as wide as it is on any other date.     */    &[aria-current="date"] {      &::after {        content: '';        position: absolute;        inset-block-end: .3125rem;        inset-inline-start: calc(50% - 1.5px);        width: 3px;        height: 3px;        border-radius: 999px;        background: currentColor;      }    }    /* A day of the month before or after, shown to complete a week; a year of the decade before or after. */    &.calendar-day-outside, &.calendar-period-outside {      color: var(--color-text-muted);    }    /* Chosen: ink, with the line of light a checked checkbox has. */    &:is([aria-selected="true"], [aria-pressed="true"]) {      background: var(--color-surface-inverse);      color: var(--color-text-inverse);      box-shadow: var(--shadow-ink-mark);    }    /* Inside a range: a chip-toned band that runs from cell to cell, rounded where a week ends. */    &.calendar-day-range {      border-radius: 0;      background: var(--color-surface-chip);      color: var(--color-text-strong);      box-shadow: none;      &:first-child {        border-start-start-radius: calc(var(--calendar-day-radius) * var(--corner-scale));        border-end-start-radius: calc(var(--calendar-day-radius) * var(--corner-scale));      }      &:last-child {        border-start-end-radius: calc(var(--calendar-day-radius) * var(--corner-scale));        border-end-end-radius: calc(var(--calendar-day-radius) * var(--corner-scale));      }    }    /*     * The ends of a range: the band covers the half of the cell that faces the range, and the ink day sits     * on it as a layer of its own, so the band meets the day's middle and not its rounded edge.     */    &:is(.calendar-day-range-start, .calendar-day-range-end) {      --calendar-band: to right;      border-radius: 0;      background: linear-gradient(var(--calendar-band), transparent 50%, var(--color-surface-chip) 0);      color: var(--color-text-inverse);      box-shadow: none;      &::before {        content: '';        position: absolute;        inset: 0;        z-index: -1;        border-radius: calc(var(--calendar-day-radius) * var(--corner-scale));        corner-shape: var(--corner-shape);        background: var(--color-surface-inverse);        box-shadow: var(--shadow-ink-mark);      }      &:dir(rtl) {        --calendar-band: to left;      }    }    &.calendar-day-range-end {      --calendar-band: to left;      &:dir(rtl) {        --calendar-band: to right;      }    }    /* A range of one day has no band, and a range that ends a week does not run past it. */    &.calendar-day-range-start:is(.calendar-day-range-end, :last-child), &.calendar-day-range-end:first-child {      background: none;    }    &:focus-visible {      @apply --focus-ring;      z-index: 1;    }    &:is(:disabled, [aria-disabled="true"]) {      color: var(--color-text-disabled);      cursor: not-allowed;    }    @media (forced-colors: active) {      /*       * A button marked aria-disabled is not one the platform knows to grey: it is given the system's disabled ink.       * A chosen day keeps its highlighted text, which the rule after this one gives it.       */      &:is(:disabled, [aria-disabled="true"]) {        color: GrayText;      }      &:is([aria-selected="true"], [aria-pressed="true"], .calendar-day-range-start, .calendar-day-range-end) {        background: Highlight;        color: HighlightText;        forced-color-adjust: none;      }      &.calendar-day-range {        outline: 1px solid Highlight;        outline-offset: -1px;      }      /*       * Focus keeps its ring in the system's color. It follows the band's outline, which would otherwise take its       * place on a day inside a range, and it is given a color because the chosen days opt out of forced colors.       */      &:focus-visible {        outline: 2px solid Highlight;        outline-offset: 2px;      }      &::before {        display: none;      }      /* Today's dot is drawn in the current color, which forced colors would turn to the canvas: it keeps the text's. */      &[aria-current="date"]::after {        forced-color-adjust: none;      }    }  }  /*   * A month or a year: four rows as tall as the weekday names and six weeks, so the grid keeps the height of a   * six-week month.   */  .calendar-period {    height: calc((var(--calendar-cell) * 6 + 1.75rem) / 4);    /* The dot of today's month or year keeps the distance it has under a day's number. */    &[aria-current="date"]::after {      inset-block-end: calc(50% - .8125rem);    }  }}