網站導覽

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" 的容器、帶有 role="tab"、aria-selected 和 aria-controls 的按鈕,以及帶有 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 中使用連結。

#可搜尋的面板

在 tabs() 的第二個引數傳入 { searchable: true },或設定框架元件的 searchable 屬性,可透過頁內搜尋與片段連結找到文字較多的未選取面板。原生 beforematch 會選取該面板對應的分頁標籤,並派送與點擊相同的事件。請把裝飾和間距放在內層元素,讓隱藏的面板不占空間。不支援 beforematch 的瀏覽器沿用一般的隱藏行為。

#React、Svelte 和 Vue

tabs 元件根據資料呈現分頁標籤清單及面板,以 ID 將各分頁標籤連到對應面板,並掛載行為,讓外部可傳入選取值並取得變更。若分頁標籤是 nav 內的連結,直接使用標記即可。執行 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" 的連結,或帶有 role="tab" 與 aria-selected 的按鈕
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;    }  }}