網站導覽

v2.1.0
表單

數字步進器

以兩側的按鈕逐步增減中間的數值,適合座位數、數量或字級等。

本頁內容

數字步進器適合座位數、數量、字級等較常逐步調整、較少直接輸入的數值。它以輸入群組包住原生的 <input type="number">,並在輸入槽兩端各放一個按鈕。請在群組加上 stepper,並在欄位加上 stepper-field。

數字步進器

<div class="sheet flex items-center gap-lg p-md pl-lg">  <label class="text-sm fg-text-strong" for="seats">Seats</label>  <div class="input-group stepper">    <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Fewer seats">      <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="M3 8L13 8" />      </svg>    </button>    <input class="input-group-field stepper-field" id="seats" type="number" min="1" max="12" value="4">    <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="More seats">      <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="M3 8L13 8" /><path d="M8 3L8 13" />      </svg>    </button>  </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 MinusIcon from '@master/icons-react/native/16/soft/minus'import PlusIcon from '@master/icons-react/native/16/soft/plus'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="sheet flex items-center gap-lg p-md pl-lg">      <label className="text-sm fg-text-strong" htmlFor="seats">Seats</label>      <div className="input-group stepper">        <button type="button" className="btn btn-square" value="-1" tabIndex={-1} aria-label="Fewer seats">          <MinusIcon className="icon" />        </button>        <input className="input-group-field stepper-field" id="seats" type="number" min="1" max="12" defaultValue="4" />        <button type="button" className="btn btn-square" value="1" tabIndex={-1} aria-label="More seats">          <PlusIcon className="icon" />        </button>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import MinusIcon from '@master/icons-svelte/native/16/soft/minus'  import PlusIcon from '@master/icons-svelte/native/16/soft/plus'</script><div class="sheet flex items-center gap-lg p-md pl-lg" {@attach attach}>  <label class="text-sm fg-text-strong" for="seats">Seats</label>  <div class="input-group stepper">    <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Fewer seats">      <MinusIcon class="icon" />    </button>    <input class="input-group-field stepper-field" id="seats" type="number" min="1" max="12" value="4">    <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="More seats">      <PlusIcon class="icon" />    </button>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import MinusIcon from '@master/icons-vue/native/16/soft/minus'import PlusIcon from '@master/icons-vue/native/16/soft/plus'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="sheet flex items-center gap-lg p-md pl-lg">    <label class="text-sm fg-text-strong" for="seats">Seats</label>    <div class="input-group stepper">      <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Fewer seats">        <MinusIcon class="icon" />      </button>      <input class="input-group-field stepper-field" id="seats" type="number" min="1" max="12" value="4">      <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="More seats">        <PlusIcon class="icon" />      </button>    </div>  </div></template>
按一下或按住按鈕、直接輸入數字,或在欄位中使用方向鍵。數值到達 1 或 12 時,對應的按鈕會以平面樣式顯示。

#欄位的原生功能

欄位採用數字輸入,因此在腳本執行前,平台就已提供步進器的大部分功能:

  • ↑ 和 ↓ 會依 step 增減數值,並在 min 和 max 停下。
  • 輔助科技會將欄位讀為數值調整按鈕,並讀出目前數值與上下限。
  • 手機會顯示數字鍵盤。
  • 手動輸入的數值超出範圍時,欄位會符合 :user-invalid,輸入槽的外框也會切換為危險色。

樣式表會隱藏瀏覽器內建的增減按鈕,改由兩側的按鈕提供相同操作。

#行為

stepper 行為讓兩側的按鈕能逐步增減中間的數值。它接受帶有 stepper 類別的根元素,以及格式化數字和拖曳調整的選項,並回傳用來解除綁定的函式。

app.js
import { stepper } from '@master/ui/behaviors/stepper.js'const root = document.querySelector('.stepper')stepper(root)root.addEventListener('change', (event) => console.log(event.target.value))
  • 逐步調整。 按鈕會呼叫欄位的 stepDown() 或 stepUp(),與方向鍵使用相同的方法,因此 min、max 和 step 只需在欄位上設定一次。
  • 上下限。 數值到達某個按鈕所對應的上限或下限時,該按鈕會進入 disabled 狀態,並在輸入槽中以平面樣式顯示。欄位留空時,視為尚未達到上限或下限。解除綁定時,會還原各按鈕原本的 disabled 狀態。
  • 按住。 按住按鈕後,經過短暫延遲便會連續調整數值,直到放開、指標移出按鈕、指標操作取消,或數值到達上限或下限。
  • 方向。 每個按鈕以 value 指定調整方向,負值代表減少。未設定時,欄位前方的按鈕會減少數值,後方的按鈕會增加數值。
  • 事件。 按鈕改變數值時,欄位會依序派送 input 和 change,與手動輸入時相同。請從欄位的 value 讀取數值。

按鈕設有 tabindex="-1",因此用 Tab 鍵瀏覽時只會停在欄位上。在欄位中按方向鍵,就能完成按鈕的操作。若未掛載行為,欄位仍保有平台原生功能,按鈕則不會改變數值。

#尺寸

數字步進器沿用輸入群組的尺寸。input-group-sm 高 32px,input-group-lg 高 44px,與相同尺寸的按鈕一致。內側的按鈕各比輸入槽矮 8px,並採用與輸入槽同心的圓角。

尺寸

<div class="input-group input-group-sm stepper">  <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Decrease">    <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="M3 8L13 8" />    </svg>  </button>  <input class="input-group-field stepper-field" type="number" value="2" aria-label="Small">  <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Increase">    <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="M3 8L13 8" /><path d="M8 3L8 13" />    </svg>  </button></div><div class="input-group stepper">  <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Decrease">    <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="M3 8L13 8" />    </svg>  </button>  <input class="input-group-field stepper-field" type="number" value="16" aria-label="Medium">  <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Increase">    <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="M3 8L13 8" /><path d="M8 3L8 13" />    </svg>  </button></div><div class="input-group input-group-lg stepper">  <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Decrease">    <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="M3 8L13 8" />    </svg>  </button>  <input class="input-group-field stepper-field" type="number" value="128" aria-label="Large">  <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Increase">    <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="M3 8L13 8" /><path d="M8 3L8 13" />    </svg>  </button></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import MinusIcon from '@master/icons-react/native/16/soft/minus'import PlusIcon from '@master/icons-react/native/16/soft/plus'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root}>      <div className="input-group input-group-sm stepper">        <button type="button" className="btn btn-square" value="-1" tabIndex={-1} aria-label="Decrease">          <MinusIcon className="icon" />        </button>        <input className="input-group-field stepper-field" type="number" defaultValue="2" aria-label="Small" />        <button type="button" className="btn btn-square" value="1" tabIndex={-1} aria-label="Increase">          <PlusIcon className="icon" />        </button>      </div>      <div className="input-group stepper">        <button type="button" className="btn btn-square" value="-1" tabIndex={-1} aria-label="Decrease">          <MinusIcon className="icon" />        </button>        <input className="input-group-field stepper-field" type="number" defaultValue="16" aria-label="Medium" />        <button type="button" className="btn btn-square" value="1" tabIndex={-1} aria-label="Increase">          <PlusIcon className="icon" />        </button>      </div>      <div className="input-group input-group-lg stepper">        <button type="button" className="btn btn-square" value="-1" tabIndex={-1} aria-label="Decrease">          <MinusIcon className="icon" />        </button>        <input className="input-group-field stepper-field" type="number" defaultValue="128" aria-label="Large" />        <button type="button" className="btn btn-square" value="1" tabIndex={-1} aria-label="Increase">          <PlusIcon className="icon" />        </button>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import MinusIcon from '@master/icons-svelte/native/16/soft/minus'  import PlusIcon from '@master/icons-svelte/native/16/soft/plus'</script><div {@attach attach}>  <div class="input-group input-group-sm stepper">    <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Decrease">      <MinusIcon class="icon" />    </button>    <input class="input-group-field stepper-field" type="number" value="2" aria-label="Small">    <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Increase">      <PlusIcon class="icon" />    </button>  </div>  <div class="input-group stepper">    <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Decrease">      <MinusIcon class="icon" />    </button>    <input class="input-group-field stepper-field" type="number" value="16" aria-label="Medium">    <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Increase">      <PlusIcon class="icon" />    </button>  </div>  <div class="input-group input-group-lg stepper">    <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Decrease">      <MinusIcon class="icon" />    </button>    <input class="input-group-field stepper-field" type="number" value="128" aria-label="Large">    <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Increase">      <PlusIcon class="icon" />    </button>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import MinusIcon from '@master/icons-vue/native/16/soft/minus'import PlusIcon from '@master/icons-vue/native/16/soft/plus'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root">    <div class="input-group input-group-sm stepper">      <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Decrease">        <MinusIcon class="icon" />      </button>      <input class="input-group-field stepper-field" type="number" value="2" aria-label="Small">      <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Increase">        <PlusIcon class="icon" />      </button>    </div>    <div class="input-group stepper">      <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Decrease">        <MinusIcon class="icon" />      </button>      <input class="input-group-field stepper-field" type="number" value="16" aria-label="Medium">      <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Increase">        <PlusIcon class="icon" />      </button>    </div>    <div class="input-group input-group-lg stepper">      <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Decrease">        <MinusIcon class="icon" />      </button>      <input class="input-group-field stepper-field" type="number" value="128" aria-label="Large">      <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Increase">        <PlusIcon class="icon" />      </button>    </div>  </div></template>

#寬度

輸入槽的寬度會配合數值。若瀏覽器支援 field-sizing: content,欄位會隨輸入的位數調整寬度,最窄可容納三位數,最寬可容納九位數。其餘瀏覽器會維持三位數的寬度。若要容納其他位數,請設定 --stepper-min 和 --stepper-max。也可以直接指定步進器的寬度,按鈕會靠在兩端,數字置中於兩者之間。

若要顯示單位,請在欄位後方加上 input-group-addon。將 step 設大,可增加每次調整的幅度。

單位與步長

<div class="input-group stepper" style="--stepper-min: 5ch">  <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Lower the budget">    <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="M3 8L13 8" />    </svg>  </button>  <input class="input-group-field stepper-field" type="number" min="0" step="250" value="1250" aria-label="Monthly budget">  <span class="input-group-addon">USD</span>  <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Raise the budget">    <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="M3 8L13 8" /><path d="M8 3L8 13" />    </svg>  </button></div><div class="input-group stepper w(280)">  <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Fewer replicas">    <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="M3 8L13 8" />    </svg>  </button>  <input class="input-group-field stepper-field" type="number" min="1" max="64" value="8" aria-label="Replicas">  <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="More replicas">    <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="M3 8L13 8" /><path d="M8 3L8 13" />    </svg>  </button></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import MinusIcon from '@master/icons-react/native/16/soft/minus'import PlusIcon from '@master/icons-react/native/16/soft/plus'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root}>      <div className="input-group stepper" style={{ '--stepper-min': '5ch' } as React.CSSProperties}>        <button type="button" className="btn btn-square" value="-1" tabIndex={-1} aria-label="Lower the budget">          <MinusIcon className="icon" />        </button>        <input className="input-group-field stepper-field" type="number" min="0" step="250" defaultValue="1250" aria-label="Monthly budget" />        <span className="input-group-addon">USD</span>        <button type="button" className="btn btn-square" value="1" tabIndex={-1} aria-label="Raise the budget">          <PlusIcon className="icon" />        </button>      </div>      <div className="input-group stepper w(280)">        <button type="button" className="btn btn-square" value="-1" tabIndex={-1} aria-label="Fewer replicas">          <MinusIcon className="icon" />        </button>        <input className="input-group-field stepper-field" type="number" min="1" max="64" defaultValue="8" aria-label="Replicas" />        <button type="button" className="btn btn-square" value="1" tabIndex={-1} aria-label="More replicas">          <PlusIcon className="icon" />        </button>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import MinusIcon from '@master/icons-svelte/native/16/soft/minus'  import PlusIcon from '@master/icons-svelte/native/16/soft/plus'</script><div {@attach attach}>  <div class="input-group stepper" style="--stepper-min: 5ch">    <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Lower the budget">      <MinusIcon class="icon" />    </button>    <input class="input-group-field stepper-field" type="number" min="0" step="250" value="1250" aria-label="Monthly budget">    <span class="input-group-addon">USD</span>    <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Raise the budget">      <PlusIcon class="icon" />    </button>  </div>  <div class="input-group stepper w(280)">    <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Fewer replicas">      <MinusIcon class="icon" />    </button>    <input class="input-group-field stepper-field" type="number" min="1" max="64" value="8" aria-label="Replicas">    <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="More replicas">      <PlusIcon class="icon" />    </button>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import MinusIcon from '@master/icons-vue/native/16/soft/minus'import PlusIcon from '@master/icons-vue/native/16/soft/plus'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root">    <div class="input-group stepper" style="--stepper-min: 5ch">      <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Lower the budget">        <MinusIcon class="icon" />      </button>      <input class="input-group-field stepper-field" type="number" min="0" step="250" value="1250" aria-label="Monthly budget">      <span class="input-group-addon">USD</span>      <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Raise the budget">        <PlusIcon class="icon" />      </button>    </div>    <div class="input-group stepper w(280)">      <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Fewer replicas">        <MinusIcon class="icon" />      </button>      <input class="input-group-field stepper-field" type="number" min="1" max="64" value="8" aria-label="Replicas">      <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="More replicas">        <PlusIcon class="icon" />      </button>    </div>  </div></template>

#格式化數字

價格、百分比或大數目寫成格式化的樣子較易閱讀:$1,250、12%、1,250,000。請把欄位和 stepper-display 放進 stepper-value,並將 format(Intl.NumberFormat 的選項)傳給行為;若數字格式應採用與頁面不同的地區設定,再傳入 locale。

app.js
stepper(root, { format: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }, locale: 'en-US' })

格式化數字

<div class="input-group stepper">  <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Lower the budget">    <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="M3 8L13 8" />    </svg>  </button>  <span class="stepper-value">    <input class="input-group-field stepper-field" type="number" min="0" step="250" value="1250" aria-label="Monthly budget">    <span class="stepper-display" aria-hidden="true"></span>  </span>  <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="Raise the budget">    <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="M3 8L13 8" /><path d="M8 3L8 13" />    </svg>  </button></div><div class="input-group stepper">  <button type="button" class="btn btn-square" value="-1" tabindex="-1" aria-label="Fewer requests">    <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="M3 8L13 8" />    </svg>  </button>  <span class="stepper-value">    <input class="input-group-field stepper-field" type="number" min="0" step="50000" value="1250000" aria-label="Requests a month">    <span class="stepper-display" aria-hidden="true"></span>  </span>  <button type="button" class="btn btn-square" value="1" tabindex="-1" aria-label="More requests">    <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="M3 8L13 8" /><path d="M8 3L8 13" />    </svg>  </button></div><script>addEventListener('DOMContentLoaded', function () {const [budget, requests] = document.querySelectorAll('.stepper')MasterUI.stepper(budget, { format: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }, locale: 'en-US' })MasterUI.stepper(requests, { locale: 'en-US' })})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
調整預算或點進欄位:欄位取得焦點時會顯示可編輯的純數字,失去焦點時會恢復格式化顯示。第二個範例未指定格式,只會將數字分組。

attach() 不會傳入任何選項,因此這個預覽會在 attach() 執行後自行呼叫 stepper;對同一個根元素再次呼叫會取代前一次。MasterUI 是預覽載入的套件;在專案中,請依照行為一節的範例匯入 stepper。

  • 欄位保留數字。 欄位未取得焦點時,顯示元素會取代欄位的位置,欄位本身的數字則為透明。欄位取得焦點時,顯示元素會讓開:讀者編輯的是 1250 而不是 $1,250,方向鍵、min、max、step、驗證和表單送出的值都和以往一樣由數字輸入欄位處理。
  • 文字。 每當數值改變,無論來自按鈕、按鍵、輸入或從外部設定的值,行為都會把格式化數字寫入顯示元素和欄位的 aria-valuetext,因此螢幕閱讀器也會讀出「$1,250」。顯示元素帶有 aria-hidden="true"。
  • 沒有格式時。 帶有 stepper-display 但沒有 format 的步進器,會依地區設定將位數分組。format 也可以是接收數字的函式,用於 Intl.NumberFormat 無法寫出的數字格式。
  • 寬度。 數字方框的寬度取欄位與顯示元素中較寬者,介於 --stepper-min 和 --stepper-max 之間,因此欄位取得焦點時按鈕不會移動。
  • 沒有腳本時,顯示元素是空的,欄位照常顯示數字。

#拖曳調整

在設計工具中,常會透過拖曳標籤來改變數字。為欄位的 <label>(可在頁面任何位置),或輸入槽中的把手加上 stepper-scrub 類別:往側邊拖曳時,每 4px 會調整一個步進,往行尾方向拖曳會增加。按住 Shift 則一次調整十個步進。

拖曳調整

<div class="flex items-center gap-md">  <label class="stepper-scrub text-sm fg-text-strong" for="opacity">Opacity</label>  <div class="input-group input-group-sm stepper">    <input class="input-group-field stepper-field" id="opacity" type="number" min="0" max="100" step="1" value="64">    <span class="input-group-addon">%</span>  </div></div><div class="input-group input-group-sm stepper" style="--stepper-min: 4ch">  <span class="input-group-addon stepper-scrub" aria-hidden="true">W</span>  <input class="input-group-field stepper-field" type="number" min="1" max="4096" value="320" aria-label="Width">  <span class="input-group-addon">px</span></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="flex items-center gap-md">        <label className="stepper-scrub text-sm fg-text-strong" htmlFor="opacity">Opacity</label>        <div className="input-group input-group-sm stepper">          <input className="input-group-field stepper-field" id="opacity" type="number" min="0" max="100" step="1" defaultValue="64" />          <span className="input-group-addon">%</span>        </div>      </div>      <div className="input-group input-group-sm stepper" style={{ '--stepper-min': '4ch' } as React.CSSProperties}>        <span className="input-group-addon stepper-scrub" aria-hidden="true">W</span>        <input className="input-group-field stepper-field" type="number" min="1" max="4096" defaultValue="320" aria-label="Width" />        <span className="input-group-addon">px</span>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div {@attach attach}>  <div class="flex items-center gap-md">    <label class="stepper-scrub text-sm fg-text-strong" for="opacity">Opacity</label>    <div class="input-group input-group-sm stepper">      <input class="input-group-field stepper-field" id="opacity" type="number" min="0" max="100" step="1" value="64">      <span class="input-group-addon">%</span>    </div>  </div>  <div class="input-group input-group-sm stepper" style="--stepper-min: 4ch">    <span class="input-group-addon stepper-scrub" aria-hidden="true">W</span>    <input class="input-group-field stepper-field" type="number" min="1" max="4096" value="320" aria-label="Width">    <span class="input-group-addon">px</span>  </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="flex items-center gap-md">      <label class="stepper-scrub text-sm fg-text-strong" for="opacity">Opacity</label>      <div class="input-group input-group-sm stepper">        <input class="input-group-field stepper-field" id="opacity" type="number" min="0" max="100" step="1" value="64">        <span class="input-group-addon">%</span>      </div>    </div>    <div class="input-group input-group-sm stepper" style="--stepper-min: 4ch">      <span class="input-group-addon stepper-scrub" aria-hidden="true">W</span>      <input class="input-group-field stepper-field" type="number" min="1" max="4096" value="320" aria-label="Width">      <span class="input-group-addon">px</span>    </div>  </div></template>
將 Opacity 標籤或第二個欄位開頭的 W 往側邊拖曳。按下但不拖曳時,仍會讓欄位取得焦點。
  • 是拖曳,不是按下。 指標移動 3px 後才開始拖曳,因此按下標籤仍會讓欄位取得焦點。結束拖曳時的點擊會被吞掉。
  • 指標鎖定。 使用滑鼠時,若瀏覽器支援,拖曳期間會鎖定指標,因此長距離拖曳永遠不會碰到螢幕邊緣;結束後指標會回到原本的位置。觸控筆或手指則改由把手擷取,在觸控螢幕上垂直滑動仍會捲動頁面。
  • 事件。 欄位每調整一步就派送 input,拖曳結束時派送一次 change。
  • 方向。 在由右至左的頁面中,往行首方向(向左)拖曳會增加。
  • 拖曳調整是為指標提供的便利功能。按鍵、按鈕和輸入都能完成它能做的事,因此它不需要自己的按鍵,把手也不列入 Tab 順序。

#停用

請同時停用欄位與兩個按鈕。輸入槽會保留原本占用的空間,數值則會以停用色顯示。若欄位已停用或為唯讀,行為不會調整數值。這個預覽只有標記,未掛載腳本。

停用

<div class="input-group stepper">  <button type="button" class="btn btn-square" tabindex="-1" aria-label="Decrease" disabled>    <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="M3 8L13 8" />    </svg>  </button>  <input class="input-group-field stepper-field" type="number" value="3" aria-label="Seats included in your plan" disabled>  <button type="button" class="btn btn-square" tabindex="-1" aria-label="Increase" disabled>    <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="M3 8L13 8" /><path d="M8 3L8 13" />    </svg>  </button></div>
import MinusIcon from '@master/icons-react/native/16/soft/minus'import PlusIcon from '@master/icons-react/native/16/soft/plus'<div className="input-group stepper">  <button type="button" className="btn btn-square" tabIndex={-1} aria-label="Decrease" disabled>    <MinusIcon className="icon" />  </button>  <input className="input-group-field stepper-field" type="number" defaultValue="3" aria-label="Seats included in your plan" disabled />  <button type="button" className="btn btn-square" tabIndex={-1} aria-label="Increase" disabled>    <PlusIcon className="icon" />  </button></div>
<script>  import MinusIcon from '@master/icons-svelte/native/16/soft/minus'  import PlusIcon from '@master/icons-svelte/native/16/soft/plus'</script><div class="input-group stepper">  <button type="button" class="btn btn-square" tabindex="-1" aria-label="Decrease" disabled>    <MinusIcon class="icon" />  </button>  <input class="input-group-field stepper-field" type="number" value="3" aria-label="Seats included in your plan" disabled>  <button type="button" class="btn btn-square" tabindex="-1" aria-label="Increase" disabled>    <PlusIcon class="icon" />  </button></div>
<script setup>import MinusIcon from '@master/icons-vue/native/16/soft/minus'import PlusIcon from '@master/icons-vue/native/16/soft/plus'</script><template>  <div class="input-group stepper">    <button type="button" class="btn btn-square" tabindex="-1" aria-label="Decrease" disabled>      <MinusIcon class="icon" />    </button>    <input class="input-group-field stepper-field" type="number" value="3" aria-label="Seats included in your plan" disabled>    <button type="button" class="btn btn-square" tabindex="-1" aria-label="Increase" disabled>      <PlusIcon class="icon" />    </button>  </div></template>

#何時使用其他元件

  • 若數字通常只輸入一次,很少調整,例如連接埠號或價格,請使用設有 type="number" 的一般輸入欄位。
  • 若要在較大的範圍內選擇位置,且操作手感比精確數值更重要,請使用滑桿。
  • 若要從少數有名稱的數量選項中擇一,請使用分段控制項。

#鍵盤操作

鍵盤操作由數字輸入欄位原生提供,行為不會新增按鍵操作。Shift 只對拖曳調整有作用。

按鍵動作
ArrowUp, ArrowDown比照數字輸入欄位,依 step 遞增或遞減,並以 min 和 max 為上下限
Shift (while scrubbing)拖曳每移動一步,數值增減十步

#無障礙

  • 請使用 <label>、表單欄位或 aria-label 為欄位加上標籤。每個按鈕都需要有自己的名稱,清楚說明會調整什麼,例如「增加座位數」,避免只寫「加號」。
  • 請將 min、max 和 step 設在欄位上。鍵盤操作、按鈕和輔助科技都會讀取這些設定。
  • 按鈕不列入 Tab 鍵的焦點順序。鍵盤使用者可在欄位中按方向鍵調整數值。指標操作區為 30px,手指則在同樣 30px 的按鈕周圍有 44px 的觸控區。
  • 格式化數字透過欄位的 aria-valuetext 播報,顯示它的元素則對輔助科技隱藏。輸入槽中的拖曳把手也會隱藏:它重複的是按鍵的功能。

#React、Svelte 和 Vue

stepper 元件會掛載行為,並接收與回傳數值。傳入 format(必要時再加上 locale)即可顯示格式化數字:它會算繪 stepper-value 和顯示元素,並預先寫好第一個數字,讓伺服器送出的 HTML 就能顯示。欄位的標籤加上 stepper-scrub 類別後,拖曳調整的方式與不使用框架時相同。執行 npx master-ui add stepper 將元件複製到專案中。元件的實作與用法請參閱 React、Svelte 和 Vue。

ui/stepper.tsx
'use client'import { useState, type ComponentProps } from 'react'import { stepper } from '@master/ui/behaviors/stepper.js'import { useBehavior } from './use-behavior'export interface StepperProps extends Omit<ComponentProps<'input'>, 'value' | 'defaultValue' | 'type'> {  /** The number; null while the field is empty. */  value?: number | null  defaultValue?: number | null  onValueChange?: (value: number | null) => void  /** The names of the two buttons, which show only an icon. */  decrementLabel: string  incrementLabel: string  /**   * Write the figure with `Intl.NumberFormat` while the field is not focused: a unit, a currency, grouping.   * The field keeps the plain number. Read when the stepper attaches, as `locale` is.   */  format?: Intl.NumberFormatOptions  /** The locale the figure is written in. The page's by default. */  locale?: string}/** * A number between two buttons. Name the field with `aria-label`, or give it an `id` a label points at; * `min`, `max`, `step` and every other prop of an input go to the field; `disabled` disables the buttons too. A * label with the `stepper-scrub` class steps the number as it is dragged sideways. */export function Stepper({ value, defaultValue, onValueChange, decrementLabel, incrementLabel, format, locale, disabled, className, ...field }: StepperProps) {  const ref = useBehavior(stepper, { format, locale }, { value, defaultValue, onValueChange })  const [first] = useState(value ?? defaultValue)  // The first figure is drawn into the first render, so the HTML a server sends shows it.  const [written] = useState(() => (format && typeof first === 'number' ? new Intl.NumberFormat(locale, format).format(first) : undefined))  const input = <input className="input-group-field stepper-field" type="number" defaultValue={first ?? undefined} aria-valuetext={written} disabled={disabled} {...field} />  return (    <div className={className ? `input-group stepper ${className}` : 'input-group stepper'} ref={ref}>      <button type="button" className="btn btn-square" value="-1" tabIndex={-1} aria-label={decrementLabel} disabled={disabled}>        <svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M3 8L13 8" /></svg>      </button>      {format        ? (            <span className="stepper-value">              {input}              <span className="stepper-display" aria-hidden="true">{written}</span>            </span>          )        : input}      <button type="button" className="btn btn-square" value="1" tabIndex={-1} aria-label={incrementLabel} disabled={disabled}>        <svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M3 8L13 8" /><path d="M8 3L8 13" /></svg>      </button>    </div>  )}
ui/Stepper.svelte
<script lang="ts" module>  import type { HTMLInputAttributes } from 'svelte/elements'  export interface StepperProps extends Omit<HTMLInputAttributes, 'value' | 'type' | 'children'> {    /** The number; null while the field is empty. Bind it, or leave it out. */    value?: number | null    onValueChange?: (value: number | null) => void    /** The names of the two buttons, which show only an icon. */    decrementLabel: string    incrementLabel: string    /**     * Write the figure with `Intl.NumberFormat` while the field is not focused: a unit, a currency, grouping.     * The field keeps the plain number. Read when the stepper attaches, as `locale` is.     */    format?: Intl.NumberFormatOptions    /** The locale the figure is written in. The page's by default. */    locale?: string  }</script><script lang="ts">  import { untrack } from 'svelte'  import { stepper } from '@master/ui/behaviors/stepper.js'  import { behavior } from './behavior.svelte.js'  let { value = $bindable(), onValueChange, decrementLabel, incrementLabel, format, locale, disabled, class: className, ...field }: StepperProps = $props()  const first = untrack(() => value)  // The first figure is drawn into the first render, so the HTML a server sends shows it.  const written = untrack(() => (format && typeof first === 'number' ? new Intl.NumberFormat(locale, format).format(first) : undefined))  const attach = behavior(stepper, () => ({ format, locale }), {    value: () => value,    change: (next) => { value = next; onValueChange?.(next) },  })</script><!--  @component  A number between two buttons. Name the field with `aria-label`, or give it an `id` a label points at;  `min`, `max`, `step` and every other prop of an input go to the field; `disabled` disables the buttons too. A  label with the `stepper-scrub` class steps the number as it is dragged sideways.--><div class={['input-group', 'stepper', className]} {@attach attach}>  <button type="button" class="btn btn-square" value="-1" tabindex={-1} aria-label={decrementLabel} {disabled}>    <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="M3 8L13 8" /></svg>  </button>  {#if format}    <span class="stepper-value">      <input class="input-group-field stepper-field" type="number" value={first ?? undefined} aria-valuetext={written} {disabled} {...field} />      <span class="stepper-display" aria-hidden="true">{written}</span>    </span>  {:else}    <input class="input-group-field stepper-field" type="number" value={first ?? undefined} {disabled} {...field} />  {/if}  <button type="button" class="btn btn-square" value="1" tabindex={-1} aria-label={incrementLabel} {disabled}>    <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="M3 8L13 8" /><path d="M8 3L8 13" /></svg>  </button></div>
ui/Stepper.vue
<script setup lang="ts">import { useAttrs, useTemplateRef } from 'vue'import { stepper } from '@master/ui/behaviors/stepper.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const props = defineProps<{  /** The names of the two buttons, which show only an icon. */  decrementLabel: string  incrementLabel: string  /**   * Write the figure with `Intl.NumberFormat` while the field is not focused: a unit, a currency, grouping.   * The field keeps the plain number. Read when the stepper attaches, as `locale` is.   */  format?: Intl.NumberFormatOptions  /** The locale the figure is written in. The page's by default. */  locale?: string  /** Disables the field and both buttons. */  disabled?: boolean}>()/** The number; null while the field is empty: `v-model`. */const model = defineModel<number | null>()/* * A number between two buttons. Name the field with `aria-label`, or give it an `id` a label points at; * `min`, `max`, `step` and every other attribute but the class go to the field; `disabled` disables the buttons * too. A label with the `stepper-scrub` class steps the number as it is dragged sideways. */const attrs = useAttrs()const field = () => {  const { class: _, ...rest } = attrs  return rest}// The first number is the field's default value, an attribute: what is typed after is not Vue's to write.const first = model.value// The first figure is drawn into the first render, so the HTML a server sends shows it.const written = props.format && typeof first === 'number' ? new Intl.NumberFormat(props.locale, props.format).format(first) : undefinedconst root = useTemplateRef<HTMLDivElement>('root')useBehavior(root, stepper, () => ({ format: props.format, locale: props.locale }), model)</script><template>  <div class="input-group stepper" :class="$attrs.class" ref="root">    <button type="button" class="btn btn-square" value="-1" tabindex="-1" :aria-label="decrementLabel" :disabled="disabled">      <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="M3 8L13 8" /></svg>    </button>    <span v-if="format" class="stepper-value">      <input class="input-group-field stepper-field" type="number" :value.attr="first ?? undefined" :aria-valuetext="written" :disabled="disabled" v-bind="field()">      <span class="stepper-display" aria-hidden="true">{{ written }}</span>    </span>    <input v-else class="input-group-field stepper-field" type="number" :value.attr="first ?? undefined" :disabled="disabled" v-bind="field()">    <button type="button" class="btn btn-square" value="1" tabindex="-1" :aria-label="incrementLabel" :disabled="disabled">      <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="M3 8L13 8" /><path d="M8 3L8 13" /></svg>    </button>  </div></template>

#類別

類別說明
stepper用於 input-group。凹槽寬度隨數值調整,兩端各有一個按鈕。到達上限或下限時,對應的按鈕會停用,並以平面樣式顯示在凹槽內。
stepper-field用於群組內的 input-group-field,採用原生數字輸入欄位。數字等寬且置中,隱藏欄位內建的增減按鈕。
stepper-value包住欄位及其 stepper-display,形成單一格,寬度取兩者中較寬者。欄位未取得焦點且 display 有數字時,欄位本身的數字會變為透明
stepper-display位於 stepper-value 中欄位之後,設有 aria-hidden="true":以 Intl.NumberFormat 格式化的數字,在欄位未取得焦點時顯示於欄位的位置。由行為寫入
stepper-scrub位於凹槽內的把手,或頁面上任何位置的欄位標籤,左右拖曳時會增減數值:游標顯示為 ew-resize,且不會選取文字

#自訂屬性

屬性預設值說明
--stepper-min3ch數字輸入欄位的最小寬度。
--stepper-max9ch使用 field-sizing 時可延展的最大寬度

#原始碼

@master/ui/components/stepper.css
/* * Stepper: a number between the two buttons that step it. * It is an input group around a native number input: the well holds a small raised button at each end, 4px in, * and the figure stands centered between them in tabular numerals. The field keeps what the platform gives a * number input: the arrow keys, min, max, step and the spinbutton role. The buttons call stepDown() and * stepUp() from a few lines of script; without it the field still types and steps from the keys. * The browser's own spin buttons are removed, since the two buttons replace them. * The well is as wide as its figure. Where field-sizing exists it follows the digits typed, between * --stepper-min and --stepper-max; elsewhere it keeps --stepper-min. * A figure written with a unit, a currency or grouping stands in a stepper-display over the field, shown while * the field is not focused; a stepper-scrub handle or label steps the number as it is dragged sideways. */@layer components.ui {  .stepper {    --stepper-min: 3ch;    --stepper-max: 9ch;    display: inline-flex;    max-width: 100%;    vertical-align: middle;    /* The buttons stand 4px from the figure's box, as they stand 4px from the well. */    gap: 4px;    cursor: default;    /* A step that has reached its limit lies flat in the well: no face, no edge, only its quiet glyph. */    .btn:disabled {      background: transparent;      box-shadow: none;    }  }  .stepper-field {    flex: 1 1 auto;    width: calc(var(--stepper-min) + 1rem);    padding-inline: .5rem;    font-weight: var(--font-weight-control);    font-variant-numeric: tabular-nums;    text-align: center;    appearance: textfield;    cursor: text;    /* Its own text cursor would otherwise stand over the group's not-allowed one. */    &:disabled {      cursor: not-allowed;    }    &::-webkit-inner-spin-button, &::-webkit-outer-spin-button {      display: none;    }    /*     * A unit after the field belongs to the figure: the digits stand at the field's end and the unit follows them     * at the gap, as one phrase.     */    &:has(+ .input-group-addon) {      padding-inline-end: 0;      text-align: end;    }    /*     * Sized by its digits, the field stops at --stepper-max even in a wider stepper. The room it leaves goes to     * either side of the figure, and of its unit when one follows, so the figure stays centered between the     * buttons and the buttons keep to the ends.     */    @supports (field-sizing: content) {      width: auto;      min-width: calc(var(--stepper-min) + 1rem);      max-width: calc(var(--stepper-max) + 1rem);      margin-inline: auto;      field-sizing: content;      &:has(+ .input-group-addon) {        margin-inline-end: 0;      }      + .input-group-addon {        margin-inline-end: auto;      }    }  }  /*   * A formatted figure: the field and its display stacked in one cell, as wide as the wider of the two. The   * field always fills the cell, so a press anywhere on the figure lands in it. While the field is not focused   * its own digits are clear and the display shows the formatted figure in the same place; while it is   * focused the display steps aside and the plain number is edited. Without the script the display is empty   * and the field shows its number as usual.   */  .stepper-value {    display: inline-grid;    flex: 1 1 auto;    align-self: stretch;    min-width: 0;    .stepper-field {      grid-area: 1 / 1;      min-width: 100%;    }    &:not(:focus-within):has(.stepper-display:not(:empty)) .stepper-field {      color: transparent;    }    &:focus-within .stepper-display {      visibility: hidden;    }    &:has(.stepper-field:disabled) .stepper-display {      color: var(--color-text-disabled);    }    /*     * Forced colors would repaint the clear digits in the field's text color, over the display's. The field     * keeps its own colors there while the display stands in for it.     */    @media (forced-colors: active) {      &:not(:focus-within):has(.stepper-display:not(:empty)) .stepper-field {        forced-color-adjust: none;      }    }  }  /* A unit stands as far from the button after it as the figure stands from the button before. */  .stepper .input-group-addon {    padding-inline-end: .5rem;  }  .stepper-display {    grid-area: 1 / 1;    align-self: center;    min-width: calc(var(--stepper-min) + 1rem);    max-width: calc(var(--stepper-max) + 1rem);    padding-inline: .5rem;    overflow: hidden;    color: var(--color-text-strong);    font-weight: var(--font-weight-control);    font-variant-numeric: tabular-nums;    text-align: center;    text-overflow: ellipsis;    white-space: nowrap;    pointer-events: none;    user-select: none;    -webkit-user-select: none;  }  /*   * A scrub handle: a handle in the well, or a label of the field anywhere in the page. Dragged sideways it   * steps the number. It keeps a vertical swipe for the page and takes the sideways one.   */  .stepper-scrub {    cursor: ew-resize;    touch-action: pan-y;    user-select: none;    -webkit-user-select: none;    -webkit-tap-highlight-color: transparent;  }  /* A field that is disabled or read-only steps nothing, so a handle in its well no longer offers to drag. */  .stepper:has(.stepper-field:is(:disabled, [readonly])) .stepper-scrub {    cursor: inherit;  }}