导航

v2.1.0
导航

标签页

在一条细线上排列标签,墨色下划线标出当前项。

本页内容

标签页的文字沿同一条细线排列,当前标签带有墨色下划线。标签页用于在同级页面或面板间切换。若要紧凑地呈现一组选项供用户选择,可使用分段控件。

浏览器支持 CSS 锚点定位时,aria-selected 变化会让同一条下划线滑到当前标签下方。下划线的上缘经过圆滑处理,避免墨色形成生硬的尖角。其他浏览器中,每个标签各自绘制下划线。

标签页

<nav class="tabs" aria-label="Project">  <a class="tabs-item" href="#overview" aria-current="page">Overview</a>  <a class="tabs-item" href="#activity">Activity</a>  <a class="tabs-item" href="#settings">Settings</a></nav>
<nav className="tabs" aria-label="Project">  <a className="tabs-item" href="#overview" aria-current="page">Overview</a>  <a className="tabs-item" href="#activity">Activity</a>  <a className="tabs-item" href="#settings">Settings</a></nav>
<nav class="tabs" aria-label="Project">  <a class="tabs-item" href="#overview" aria-current="page">Overview</a>  <a class="tabs-item" href="#activity">Activity</a>  <a class="tabs-item" href="#settings">Settings</a></nav>
<template>  <nav class="tabs" aria-label="Project">    <a class="tabs-item" href="#overview" aria-current="page">Overview</a>    <a class="tabs-item" href="#activity">Activity</a>    <a class="tabs-item" href="#settings">Settings</a>  </nav></template>

#带计数

带计数

<nav class="tabs" aria-label="Repository">  <a class="tabs-item" href="#code" aria-current="page">Code</a>  <a class="tabs-item" href="#issues">Issues <span class="badge badge-sm badge-pill">24</span></a>  <a class="tabs-item" href="#pulls">    Pull requests <span class="badge badge-sm badge-pill">3</span>  </a></nav>
<nav className="tabs" aria-label="Repository">  <a className="tabs-item" href="#code" aria-current="page">Code</a>  <a className="tabs-item" href="#issues">    Issues <span className="badge badge-sm badge-pill">24</span>  </a>  <a className="tabs-item" href="#pulls">    Pull requests <span className="badge badge-sm badge-pill">3</span>  </a></nav>
<nav class="tabs" aria-label="Repository">  <a class="tabs-item" href="#code" aria-current="page">Code</a>  <a class="tabs-item" href="#issues">Issues <span class="badge badge-sm badge-pill">24</span></a>  <a class="tabs-item" href="#pulls">    Pull requests <span class="badge badge-sm badge-pill">3</span>  </a></nav>
<template>  <nav class="tabs" aria-label="Repository">    <a class="tabs-item" href="#code" aria-current="page">Code</a>    <a class="tabs-item" href="#issues">Issues <span class="badge badge-sm badge-pill">24</span></a>    <a class="tabs-item" href="#pulls">      Pull requests <span class="badge badge-sm badge-pill">3</span>    </a>  </nav></template>

#小尺寸

小尺寸

<nav class="tabs tabs-sm" aria-label="Period">  <a class="tabs-item" href="#day">Day</a>  <a class="tabs-item" href="#week" aria-current="page">Week</a>  <a class="tabs-item" href="#month">Month</a></nav>
<nav className="tabs tabs-sm" aria-label="Period">  <a className="tabs-item" href="#day">Day</a>  <a className="tabs-item" href="#week" aria-current="page">Week</a>  <a className="tabs-item" href="#month">Month</a></nav>
<nav class="tabs tabs-sm" aria-label="Period">  <a class="tabs-item" href="#day">Day</a>  <a class="tabs-item" href="#week" aria-current="page">Week</a>  <a class="tabs-item" href="#month">Month</a></nav>
<template>  <nav class="tabs tabs-sm" aria-label="Period">    <a class="tabs-item" href="#day">Day</a>    <a class="tabs-item" href="#week" aria-current="page">Week</a>    <a class="tabs-item" href="#month">Month</a>  </nav></template>

#标签页面板

在同一页面内切换面板时,遵循 WAI-ARIA 标签页模式:使用 role="tablist" 容器、带有 aria-selected 和 aria-controls 的 role="tab" 按钮,以及 role="tabpanel" 区域。样式表绘制所有状态,tabs 行为脚本 负责切换面板,并为标签列表提供键盘操作。

标签列表

<div class="tabs" role="tablist" aria-label="Account">  <button type="button" class="tabs-item" role="tab" id="tab-profile" aria-selected="true" aria-controls="panel-profile">    Profile  </button>  <button type="button" class="tabs-item" role="tab" id="tab-billing" aria-selected="false" aria-controls="panel-billing" tabindex="-1">    Billing  </button>  <button type="button" class="tabs-item" role="tab" id="tab-members" aria-selected="false" aria-controls="panel-members" tabindex="-1">    Members  </button></div><div role="tabpanel" tabindex="0" id="panel-profile" aria-labelledby="tab-profile" class="pt-md text-sm fg-text-body">  Profile settings</div><div role="tabpanel" tabindex="0" id="panel-billing" aria-labelledby="tab-billing" class="pt-md text-sm fg-text-body" hidden>  Billing settings</div><div role="tabpanel" tabindex="0" id="panel-members" aria-labelledby="tab-members" class="pt-md text-sm fg-text-body" hidden>  Members of the workspace</div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root}>      <div className="tabs" role="tablist" aria-label="Account">        <button type="button" className="tabs-item" role="tab" id="tab-profile" aria-selected="true" aria-controls="panel-profile">          Profile        </button>        <button type="button" className="tabs-item" role="tab" id="tab-billing" aria-selected="false" aria-controls="panel-billing" tabIndex={-1}>          Billing        </button>        <button type="button" className="tabs-item" role="tab" id="tab-members" aria-selected="false" aria-controls="panel-members" tabIndex={-1}>          Members        </button>      </div>      <div role="tabpanel" tabIndex={0} id="panel-profile" aria-labelledby="tab-profile" className="pt-md text-sm fg-text-body">        Profile settings      </div>      <div role="tabpanel" tabIndex={0} id="panel-billing" aria-labelledby="tab-billing" className="pt-md text-sm fg-text-body" hidden>        Billing settings      </div>      <div role="tabpanel" tabIndex={0} id="panel-members" aria-labelledby="tab-members" className="pt-md text-sm fg-text-body" hidden>        Members of the workspace      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div {@attach attach}>  <div class="tabs" role="tablist" aria-label="Account">    <button type="button" class="tabs-item" role="tab" id="tab-profile" aria-selected="true" aria-controls="panel-profile">      Profile    </button>    <button type="button" class="tabs-item" role="tab" id="tab-billing" aria-selected="false" aria-controls="panel-billing" tabindex="-1">      Billing    </button>    <button type="button" class="tabs-item" role="tab" id="tab-members" aria-selected="false" aria-controls="panel-members" tabindex="-1">      Members    </button>  </div>  <div role="tabpanel" tabindex="0" id="panel-profile" aria-labelledby="tab-profile" class="pt-md text-sm fg-text-body">    Profile settings  </div>  <div role="tabpanel" tabindex="0" id="panel-billing" aria-labelledby="tab-billing" class="pt-md text-sm fg-text-body" hidden>    Billing settings  </div>  <div role="tabpanel" tabindex="0" id="panel-members" aria-labelledby="tab-members" class="pt-md text-sm fg-text-body" hidden>    Members of the workspace  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root">    <div class="tabs" role="tablist" aria-label="Account">      <button type="button" class="tabs-item" role="tab" id="tab-profile" aria-selected="true" aria-controls="panel-profile">        Profile      </button>      <button type="button" class="tabs-item" role="tab" id="tab-billing" aria-selected="false" aria-controls="panel-billing" tabindex="-1">        Billing      </button>      <button type="button" class="tabs-item" role="tab" id="tab-members" aria-selected="false" aria-controls="panel-members" tabindex="-1">        Members      </button>    </div>    <div role="tabpanel" tabindex="0" id="panel-profile" aria-labelledby="tab-profile" class="pt-md text-sm fg-text-body">      Profile settings    </div>    <div role="tabpanel" tabindex="0" id="panel-billing" aria-labelledby="tab-billing" class="pt-md text-sm fg-text-body" hidden>      Billing settings    </div>    <div role="tabpanel" tabindex="0" id="panel-members" aria-labelledby="tab-members" class="pt-md text-sm fg-text-body" hidden>      Members of the workspace    </div>  </div></template>
聚焦一个标签后,可使用方向键、Home 或 End 键。也可单击选中标签。

tabs 接收标签页列表,并返回卸载行为的函数。

app.js
import { tabs } from '@master/ui/behaviors/tabs.js'const detach = tabs(document.querySelector('.tabs[role="tablist"]'))
  • Tab 键只停一处。 只有选中的标签位于 Tab 键的焦点顺序中。方向键将焦点移到上一个或下一个标签并选中它,跳过禁用的标签,到达首尾时循环切换。Home 和 End 分别跳到第一个和最后一个标签。带有 aria-orientation="vertical" 的标签列表使用上、下方向键。
  • 面板。 标签通过 aria-controls 指定对应的面板。选中标签的面板会显示,其余面板会加上 hidden。
  • 值。 选中另一个标签时,标签列表会依次派发 input 和 change。两个事件都会冒泡,两者的 detail.value 都取该标签的 data-value,若无则取其文本。行为脚本返回的函数也有同样的 value,从外部设置它即可选中对应标签,此时不会派发任何事件。
  • 没有脚本时,只有选中标签的面板不带 hidden,面板也无法切换。如果每个标签都可以对应一个独立页面,可在 nav 中使用链接。

#可搜索的面板

将 { searchable: true } 作为 tabs() 的第二个参数,或设置框架组件的 searchable 属性,即可通过页内查找与片段导航打开文字较多的未选中面板。原生 beforematch 会选中显示出来的面板对应的标签页,并发出与点击相同的事件。请把装饰和间距放在内层元素上,让隐藏的面板不占空间。不支持 beforematch 的浏览器沿用普通的隐藏行为。

#React、Svelte 和 Vue

tabs 组件根据数据渲染标签列表及其面板,通过 ID 将各标签与对应面板关联起来,挂载行为脚本,并支持从外部传入和读取当前选中的标签。若标签是 nav 中的链接,直接使用 HTML 标记即可。使用 npx master-ui add tabs 将组件复制到项目中。React、Svelte 和 Vue 介绍了这些组件的实现和用法。

ui/tabs.tsx
'use client'import { useId, useState, type ComponentProps, type ReactNode } from 'react'import { tabs } from '@master/ui/behaviors/tabs.js'import { useBehavior } from './use-behavior'export interface Tab {  /** What selecting the tab gives `onValueChange`. */  value: string  label: ReactNode  /** The panel the tab shows. */  content: ReactNode  disabled?: boolean}export interface TabsProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'children' | 'role' | 'ref'> {  tabs: Tab[]  /** The value of the selected tab. The first tab by default. */  value?: string  defaultValue?: string  onValueChange?: (value: string) => void  /** Let Find in Page and fragment links reveal inactive panels where supported. */  searchable?: boolean  /** Classes for each panel, such as its padding. */  panelClassName?: string}/** Tabs that switch panels in place. Name the tablist with `aria-label` or `aria-labelledby`. */export function Tabs({ tabs: list, value, defaultValue, onValueChange, searchable, panelClassName, className, ...root }: TabsProps) {  const id = useId()  const ref = useBehavior(tabs, { searchable }, { value, defaultValue, onValueChange: onValueChange as ((value: string | null) => void) | undefined })  const [first] = useState(value ?? defaultValue ?? list.find(tab => !tab.disabled)?.value)  return (    <>      <div className={className ? `tabs ${className}` : 'tabs'} role="tablist" ref={ref} {...root}>        {list.map((tab, index) => (          <button type="button" className="tabs-item" role="tab" key={tab.value} id={`${id}tab${index}`} data-value={tab.value} aria-selected={tab.value === first} aria-controls={`${id}panel${index}`} tabIndex={tab.value === first ? 0 : -1} disabled={tab.disabled}>{tab.label}</button>        ))}      </div>      {list.map((tab, index) => (        <div className={panelClassName} role="tabpanel" key={tab.value} id={`${id}panel${index}`} aria-labelledby={`${id}tab${index}`} hidden={tab.value !== first}>{tab.content}</div>      ))}    </>  )}
ui/Tabs.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLAttributes } from 'svelte/elements'  export interface Tab {    /** What selecting the tab gives `onValueChange`. */    value: string    label: string    /** The panel the tab shows, as text. Leave it out when `panel` writes it. */    content?: string    disabled?: boolean  }  export interface TabsProps extends Omit<HTMLAttributes<HTMLDivElement>, 'role' | 'children'> {    tabs: Tab[]    /** The value of the selected tab. Bind it, or leave it out: the first tab is selected. */    value?: string    onValueChange?: (value: string) => void    /** Let Find in Page and fragment links reveal inactive panels where supported. */    searchable?: boolean    /** Writes the panel of a tab, when it is more than text. */    panel?: Snippet<[Tab]>    /** Classes for each panel, such as its padding. */    panelClass?: string  }</script><script lang="ts">  import { untrack } from 'svelte'  import { tabs } from '@master/ui/behaviors/tabs.js'  import { behavior } from './behavior.svelte.js'  let { tabs: list, value = $bindable(), onValueChange, searchable, panel, panelClass, class: className, ...root }: TabsProps = $props()  const id = $props.id()  // The first value is drawn into the first render; after that the behavior marks the selected tab. A tab  // written later, from new tabs, is drawn with the value as it is then, which is not read as state.  const selected = { value: untrack(() => value ?? list.find(tab => !tab.disabled)?.value) }  const attach = behavior(tabs, () => ({ searchable }), {    value: () => value,    change: (next) => {      if (next === null) return      selected.value = next      value = next      onValueChange?.(next)    },    settled: (held) => { if (held !== null) selected.value = held },  })</script><!--  @component  Tabs that switch panels in place. Name the tablist with `aria-label` or `aria-labelledby`.--><div class={['tabs', className]} role="tablist" {@attach attach} {...root}>  {#each list as tab, index (tab.value)}    <button type="button" class="tabs-item" role="tab" id="{id}tab{index}" data-value={tab.value} aria-selected={tab.value === selected.value} aria-controls="{id}panel{index}" tabindex={tab.value === selected.value ? 0 : -1} disabled={tab.disabled}>{tab.label}</button>  {/each}</div>{#each list as tab, index (tab.value)}  <div class={panelClass} role="tabpanel" id="{id}panel{index}" aria-labelledby="{id}tab{index}" hidden={tab.value !== selected.value}>    {#if panel}{@render panel(tab)}{:else}{tab.content}{/if}  </div>{/each}
ui/Tabs.vue
<script lang="ts">export interface Tab {  /** What selecting the tab gives the model. */  value: string  label: string  /** The panel the tab shows, as text. The `panel` slot writes richer panels. */  content?: string  disabled?: boolean}</script><script setup lang="ts">import { useId, useTemplateRef } from 'vue'import { tabs as tablist } from '@master/ui/behaviors/tabs.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const props = defineProps<{  tabs: Tab[]  /** Let Find in Page and fragment links reveal inactive panels where supported. */  searchable?: boolean  /** Classes for each panel, such as its padding. */  panelClass?: string}>()/** The value of the selected tab: `v-model`. The first tab by default. */const model = defineModel<string>()defineSlots<{  /** What a tab's panel holds, in place of its `content`. */  panel?: (scope: { tab: Tab }) => unknown}>()/* Tabs that switch panels in place. Name the tablist with `aria-label` or `aria-labelledby`. */const id = useId()const first = model.value ?? props.tabs.find(tab => !tab.disabled)?.valueconst root = useTemplateRef<HTMLDivElement>('root')useBehavior(root, tablist, () => ({ searchable: props.searchable }), model)</script><template>  <div class="tabs" role="tablist" ref="root" v-bind="$attrs">    <button v-for="(tab, index) in tabs" :key="tab.value" type="button" class="tabs-item" role="tab" :id="`${id}-tab-${index}`" :data-value="tab.value" :aria-selected="tab.value === first" :aria-controls="`${id}-panel-${index}`" :tabindex="tab.value === first ? 0 : -1" :disabled="tab.disabled">{{ tab.label }}</button>  </div>  <div v-for="(tab, index) in tabs" :key="tab.value" v-bind="panelClass ? { class: panelClass } : {}" role="tabpanel" :id="`${id}-panel-${index}`" :aria-labelledby="`${id}-tab-${index}`" :hidden="tab.value !== first"><slot name="panel" :tab="tab">{{ tab.content }}</slot></div></template>

#类名

类名说明
tabs带细线的选项卡栏,可用于具有无障碍名称的 nav 或带 role="tablist" 的元素。选项卡放不下时,选项卡栏可横向滚动。
tabs-item选项卡可用带 aria-current="page" 的链接,或带 aria-selected 的 role="tab" 按钮
tabs-sm紧凑选项卡高 36px,标签字号为 13px。默认高度为 44px,标签字号为 14px。与 tabs 一同使用

#源码

@master/ui/components/tabs.css
/* * Tabs: words on one hairline; the current one is underlined in ink. * The current tab keeps its weight so the row never shifts between states. * With anchor positioning the underline is one mark that glides to the current tab. */@layer components.ui {  .tabs {    --tabs-item-height: 2.75rem;    --tabs-gap: 1.5rem;    --tabs-font-size: .875rem;    --icon-size: 1rem;    display: flex;    gap: 0 var(--tabs-gap);    overflow-x: auto;    overscroll-behavior-x: contain;    box-shadow: inset 0 -1px 0 var(--color-line-divider);    scrollbar-width: none;    /* The script listens on the whole row: a tap in the space between tabs must not flash it grey on iOS. */    -webkit-tap-highlight-color: transparent;    &.tabs-sm {      --tabs-item-height: 2.25rem;      --tabs-gap: 1rem;      --tabs-font-size: .8125rem;      --icon-size: .875rem;    }    @media (forced-colors: active) {      border-bottom: 1px solid CanvasText;    }  }  /* A tab: a link with aria-current="page", or a role="tab" button with aria-selected="true". */  .tabs-item {    display: inline-flex;    flex: none;    align-items: center;    gap: .375rem;    min-height: var(--tabs-item-height);    margin: 0;    padding: 0;    border: 0;    border-radius: 0;    background: none;    color: var(--color-text-muted);    font: 400 var(--tabs-font-size)/1.4 var(--font-family-sans);    font-feature-settings: inherit;    text-decoration: none;    white-space: nowrap;    appearance: none;    -webkit-tap-highlight-color: transparent;    cursor: pointer;    touch-action: manipulation;    transition-property: color, box-shadow;    transition-duration: var(--duration-quick);    transition-timing-function: var(--easing-glide);    user-select: none;    -webkit-user-select: none;    @media (hover: hover) {      &:hover:not(:disabled, [aria-disabled="true"]) {        color: var(--color-text-strong);      }    }    /* Pressed: the strong ink, as under the pointer, so a tap is answered too. */    &:active:not(:disabled, [aria-disabled="true"]) {      color: var(--color-text-strong);    }    &:is([aria-current="page"], [aria-selected="true"]) {      color: var(--color-text-strong);      box-shadow: inset 0 -2px 0 var(--color-text-strong);    }    &:focus-visible {      @apply --focus-ring;      outline-offset: -2px;      border-radius: calc((var(--radius-chip) - 2px) * var(--corner-scale));      corner-shape: var(--corner-shape);    }    /*     * Disabled: the disabled ink and no answer to the pointer. It still takes the pointer, so a tooltip that says     * why it is unavailable can be reached on it.     */    &:is(:disabled, [aria-disabled="true"]) {      color: var(--color-text-disabled);      cursor: not-allowed;    }    @media (forced-colors: active) {      &:is([aria-current="page"], [aria-selected="true"]) {        border-bottom: 2px solid Highlight;      }    }  }  /*   * The gliding underline. The current tab names itself as an anchor; the row scopes that name and draws one   * mark between the anchor's edges, with a softened top so the ink does not end in a hard corner.   */  @supports (anchor-scope: --tabs-mark) {    .tabs {      position: relative;      anchor-scope: --tabs-mark;      &:has(.tabs-item:is([aria-current="page"], [aria-selected="true"]))::after {        content: '';        position: absolute;        position-anchor: --tabs-mark;        right: anchor(right);        bottom: 0;        left: anchor(left);        height: 2px;        border-radius: 2px 2px 0 0;        background: var(--color-text-strong);        pointer-events: none;        transition-property: right, left;        transition-duration: var(--duration-base);        transition-timing-function: var(--easing-glide);      }      /* As heavy as the rule that glides, or the glide outweighs it. */      @media (prefers-reduced-motion: reduce) {        &:has(.tabs-item:is([aria-current="page"], [aria-selected="true"]))::after {          transition: none;        }      }      @media (forced-colors: active) {        &::after {          display: none;        }      }    }    .tabs-item:is([aria-current="page"], [aria-selected="true"]) {      anchor-name: --tabs-mark;      box-shadow: none;    }  }}