Number Input
输入数字,按步进调整值,并按语言格式化显示。
把 Number Input 用于数量、价格和度量。它保留一个数值,同时显示格式化后的文本,并可以用键盘、步进按钮或拖动它的标签来调整这个值。
<script lang="ts">
import { MinusIcon, MoveHorizontalIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import {
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
NumberInputScrubArea,
NumberInputScrubAreaCursor,
} from "@ui-sdk/svelte/number-input"
import { useLog } from "./log"
const log = useLog()
</script>
<Field>
<NumberInput
defaultValue={1}
min={1}
onValueCommit={(value) => log(`Quantity ${value ?? "empty"}`)}
>
<NumberInputScrubArea pixelsPerStep={4}>
<FieldLabel>Quantity</FieldLabel>
<NumberInputScrubAreaCursor>
<MoveHorizontalIcon aria-hidden="true" />
</NumberInputScrubAreaCursor>
</NumberInputScrubArea>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
</Field>安装
npm install @ui-sdk/svelte @ui-sdk/core组合
用下面的组合构建 NumberInput:
NumberInput
├── NumberInputScrubArea
│ └── NumberInputScrubAreaCursor
└── NumberInputGroup
├── NumberInputDecrement
├── NumberInputControl
└── NumberInputIncrementNumberInput 持有数值。NumberInputGroup 包住文本输入框和可选的步进按钮。NumberInputControl 渲染输入框;NumberInputDecrement 和 NumberInputIncrement 改变它的值,并在按住时重复。NumberInputScrubArea 是可选的,拖动它时会改变值。
输入的文字有效且在边界内时,输入会更新值。Enter 或失去焦点会提交它:文本被解析、限制在边界内、吸附到步进,然后格式化。空的输入框值为 null。
用法
导入部件并把它们组合起来:
<script lang="ts">
import {
NumberInput,
NumberInputGroup,
NumberInputControl,
NumberInputDecrement,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
</script>
<NumberInput defaultValue={1} min={0}>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">−</NumberInputDecrement>
<NumberInputControl aria-label="Quantity" />
<NumberInputIncrement aria-label="Increase">+</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>字段
把数字输入框包进 Field,给它一个可见的标签和描述。
<script lang="ts">
import { MinusIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
import {
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
</script>
<Field>
<FieldLabel>Tickets</FieldLabel>
<NumberInput defaultValue={2} min={1}>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
<FieldDescription
>Each ticket admits one person to the workshop.</FieldDescription
>
</Field>最小值与最大值
用 min 和 max 设置边界。步进按钮到达边界时会禁用。输入的值超出边界时,会在提交时被限制到边界内。
<script lang="ts">
import { MinusIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
import {
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
</script>
<Field>
<FieldLabel>Guests</FieldLabel>
<NumberInput defaultValue={2} min={1} max={8}>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
<FieldDescription>Tables seat between 1 and 8 guests.</FieldDescription>
</Field>步进与大步进
step 设置通常的增量,默认是 1。步进从 min 开始计算,没有设置最小值时从 0 开始。当步进落不到 max 上时,End 和增加按钮会停在它下方的最高步进位置,所以步进会让值保持在步进网格上,和 Slider 一样。Shift、Page Up 和 Page Down 使用 largeStep,默认十个步进;Alt(Option)加方向键使用 smallStep,即十分之一个步进。键盘列出了每个按键。
<script lang="ts">
import { MinusIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
import {
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
</script>
<Field>
<FieldLabel>Hours</FieldLabel>
<NumberInput
defaultValue={1.5}
min={0}
max={24}
step={0.25}
largeStep={1}
smallStep={0.05}
>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
<FieldDescription>Logged in quarter hours.</FieldDescription>
</Field>格式化
通过 format 传入 Intl.NumberFormat 选项。输入框按这个格式显示和解析,同时保留数值。对于百分比,0.15 会显示为 15%,step 默认采用格式能显示的最小百分比:整数百分比是 0.01,两位小数是 0.0001。
<script lang="ts">
import { MinusIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import {
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
const fields = [
{
label: "Price",
defaultValue: 19.99,
step: 0.01,
format: { style: "currency", currency: "USD" },
},
{
label: "Discount",
defaultValue: 0.15,
step: 0.01,
format: { style: "percent" },
},
{
label: "Weight",
defaultValue: 2.5,
step: 0.1,
format: { style: "unit", unit: "kilogram" },
},
] satisfies {
label: string
defaultValue: number
step: number
format: Intl.NumberFormatOptions
}[]
</script>
<div data-slot="stack">
{#each fields as field (field.label)}
<Field>
<FieldLabel>{field.label}</FieldLabel>
<NumberInput
defaultValue={field.defaultValue}
step={field.step}
format={field.format}
min={0}
>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
</Field>
{/each}
</div>语言
设置 locale 来选择分隔符、货币符号和分组。不设置时,输入框在挂载后跟随页面的语言或浏览器的语言。没有提供 locale 时,服务端标记使用英语;如果首次渲染的结果很重要,请显式设置 locale。
<script lang="ts">
import { MinusIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
import {
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
const fields = [
{
label: "Preis",
locale: "de-DE",
defaultValue: 1234.5,
step: 0.01,
format: { style: "currency", currency: "EUR" },
},
{
label: "Budget",
locale: "en-IN",
defaultValue: 1234567,
step: 1000,
format: { style: "currency", currency: "INR", maximumFractionDigits: 0 },
},
] satisfies {
label: string
locale: string
defaultValue: number
step: number
format: Intl.NumberFormatOptions
}[]
</script>
<div data-slot="stack">
{#each fields as field (field.label)}
<Field>
<FieldLabel>{field.label}</FieldLabel>
<NumberInput
defaultValue={field.defaultValue}
step={field.step}
format={field.format}
locale={field.locale}
min={0}
>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
<FieldDescription>Formatted for {field.locale}.</FieldDescription>
</Field>
{/each}
</div>鼠标滚轮
设置 wheel,让输入框获得焦点时可以用鼠标滚轮步进。它默认关闭。
<script lang="ts">
import { MinusIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
import {
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
</script>
<Field>
<FieldLabel>Font size</FieldLabel>
<NumberInput defaultValue={16} min={8} max={72} wheel>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
<FieldDescription>Focus the input, then scroll over it.</FieldDescription>
</Field>拖动区域
NumberInputScrubArea 在你拖动它时改变值。手柄可以是数字输入框里的任何元素:第一个示例里的标签,或者组里的字母或图标,就像设计工具那样。向右和向上会增大值。orientation 选择轴,pixelsPerStep 控制指针每步移动多远。Shift 和 Alt(Option)使用大步进和小步进。
<script lang="ts">
import { MoveHorizontalIcon } from "@lucide/svelte"
import {
NumberInput,
NumberInputControl,
NumberInputGroup,
NumberInputScrubArea,
NumberInputScrubAreaCursor,
} from "@ui-sdk/svelte/number-input"
import { useLog } from "./log"
const fields = [
{ label: "X position", handle: "X", defaultValue: 120 },
{ label: "Y position", handle: "Y", defaultValue: 48 },
{ label: "Width", handle: "W", defaultValue: 320, min: 0 },
{ label: "Height", handle: "H", defaultValue: 240, min: 0 },
]
const log = useLog()
const title = $props.id()
</script>
<div data-slot="card" role="group" aria-labelledby={title}>
<h3 id={title}>Frame</h3>
<div data-slot="grid">
{#each fields as { label, handle, ...options } (label)}
<NumberInput
{...options}
onValueCommit={(value) => log(`${label} ${value ?? "empty"}`)}
>
<NumberInputGroup>
<NumberInputScrubArea pixelsPerStep={1}>
<span aria-hidden="true">{handle}</span>
<NumberInputScrubAreaCursor>
<MoveHorizontalIcon aria-hidden="true" />
</NumberInputScrubAreaCursor>
</NumberInputScrubArea>
<NumberInputControl aria-label={label} />
</NumberInputGroup>
</NumberInput>
{/each}
</div>
</div>指针锁定可用时,拖动可以一直继续,越过屏幕边缘。NumberInputScrubAreaCursor 在锁定时绘制一个替代光标。光标用一个内联位移放进文档 body 中;用负外边距让图标居中。
要把拖动区域放在数字输入框之外,比如放在工具栏里的图标上,给两者传同一个控制器。多个拖动区域可以控制同一个字段。
禁用
在组件或包住它的 fieldset 上设置 disabled,阻止聚焦、变更和表单提交。
<Field>
<FieldLabel>Quantity</FieldLabel>
<NumberInput defaultValue={3} disabled>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">−</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">+</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
<FieldDescription>Sold out. You can't change the quantity.</FieldDescription>
</Field>在某一个步进按钮上设置 disabled,只关闭那个方向。另一个按钮仍然可以步进。
只读
设置 readOnly,让值保持可聚焦、仍包含在表单数据中,同时阻止编辑和步进。
<Field>
<FieldLabel>Seats included</FieldLabel>
<NumberInput defaultValue={5} readOnly>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">−</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">+</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
<FieldDescription>Set by your plan.</FieldDescription>
</Field>校验
用 required 阻止空值。Field 把它的错误与输入框关联,并在一次不成功的提交后把它标记为无效。这里,Age 为空时选择 Continue,会显示 “Enter your age.”。
<form>
<Field>
<FieldLabel>Age</FieldLabel>
<NumberInput name="age" required min={18} max={120}>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">−</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">+</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
<FieldError match="valueMissing">Enter your age.</FieldError>
</Field>
<button type="submit">Continue</button>
</form>受控
用 bind:value 绑定 value,并用 onValueChange 获取原因。交互进行中时,onValueChange 报告有效的变更。onValueCommit 在输入的文字被提交、步进按键或按钮松开,或拖动结束时运行。用提交事件来做交互结束后才该做的事。
<script lang="ts">
import { MinusIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import {
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
import { useLog } from "./log"
const log = useLog()
let value = $state<number | null>(4)
</script>
<div data-slot="stack">
<div data-slot="controls">
<button type="button" onclick={() => (value = 4)}>Reset to 4</button>
<button type="button" onclick={() => (value = null)}>Clear</button>
</div>
<Field>
<FieldLabel>Servings</FieldLabel>
<NumberInput
bind:value
onValueChange={(next, details) =>
log(`Value ${next ?? "empty"} (${details.reason})`)}
onValueCommit={(next, details) =>
log(`Committed ${next ?? "empty"} (${details.reason})`)}
min={1}
max={12}
>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
</Field>
</div>共享的状态约定见状态与事件,Number Input 特有的原因见原因。
控制器
用 createNumberInputController() 创建一个控制器,并作为 controller 传入,从其他控件改变或聚焦输入框。increment() 和 decrement() 步进值;传入 { large: true } 使用大步进。setValue()、getValue() 和 focus() 负责直接更新和读取。
<script lang="ts">
import { MinusIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import {
createNumberInputController,
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
import { useLog } from "./log"
const log = useLog()
const zoom = createNumberInputController()
</script>
<div data-slot="stack">
<div data-slot="controls">
<button type="button" onclick={() => zoom.decrement({ large: true })}
>Zoom Out</button
>
<button type="button" onclick={() => zoom.increment({ large: true })}
>Zoom In</button
>
<button type="button" onclick={() => zoom.setValue(100)}>Actual Size</button
>
<button type="button" onclick={() => log(`Zoom is ${zoom.getValue()}%`)}
>Read</button
>
<button type="button" onclick={() => zoom.focus()}>Focus</button>
</div>
<Field>
<FieldLabel>Zoom</FieldLabel>
<NumberInput
defaultValue={100}
min={10}
max={400}
step={10}
format={{ style: "unit", unit: "percent" }}
controller={zoom}
onValueChange={(value, details) =>
log(`Zoom ${value ?? "empty"}% (${details.reason})`)}
>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
</Field>
</div>控制器介绍了创建和共享控制器。
表单
一个隐藏的输入框以 name 提交纯数值。格式化不会改变表单数据:显示为 $4.50 的金额仍然提交 4.5。空值提交空字符串。
<script lang="ts">
import { MinusIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import {
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
import { useLog } from "./log"
const log = useLog()
const form = $props.id()
function onsubmit(event: SubmitEvent & { currentTarget: HTMLFormElement }) {
event.preventDefault()
const data = [...new FormData(event.currentTarget)].map(
([name, value]) => `${name}=${value}`
)
log(`Submitted ${data.join(", ")}`)
}
</script>
<div data-slot="stack">
<form data-slot="stack" id={form} {onsubmit}>
<Field>
<FieldLabel>Quantity</FieldLabel>
<NumberInput name="quantity" defaultValue={2} min={1}>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
</Field>
<Field>
<FieldLabel>Tip</FieldLabel>
<NumberInput
name="tip"
defaultValue={4.5}
min={0}
step={0.5}
format={{ style: "currency", currency: "USD" }}
>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
</Field>
</form>
<Field>
<FieldLabel>Gift cards</FieldLabel>
<NumberInput name="gift-cards" {form} defaultValue={0} min={0}>
<NumberInputGroup>
<NumberInputDecrement aria-label="Decrease">
<MinusIcon aria-hidden="true" />
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Increase">
<PlusIcon aria-hidden="true" />
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
</Field>
<div data-slot="row">
<button type="reset" {form}>Reset</button>
<button type="submit" {form} data-variant="solid">Save</button>
</div>
</div>设置 form,把输入框和页面其他位置的一个表单关联起来。表单重置会恢复默认值,并报告 reset 原因。
自定义渲染
每个部件都接受一个 render snippet,它收到要展开的 props 和部件的状态,children snippet 收到状态。这里减少按钮加了一个 tooltip,增加按钮在值到达边界后显示 Max。
<script lang="ts">
import { MinusIcon, PlusIcon } from "@lucide/svelte"
import { Field, FieldLabel } from "@ui-sdk/svelte/field"
import {
NumberInput,
NumberInputControl,
NumberInputDecrement,
NumberInputGroup,
NumberInputIncrement,
} from "@ui-sdk/svelte/number-input"
</script>
<Field>
<FieldLabel>Temperature</FieldLabel>
<NumberInput
defaultValue={-2}
min={-20}
max={40}
format={{ style: "unit", unit: "celsius" }}
>
<NumberInputGroup>
<NumberInputDecrement aria-label="Colder">
{#snippet render({ props, state })}
<button
{...props}
title={state.atBound ? "As cold as it goes" : "Colder"}
>
<MinusIcon aria-hidden="true" />
</button>
{/snippet}
</NumberInputDecrement>
<NumberInputControl />
<NumberInputIncrement aria-label="Warmer">
{#snippet children(state)}
{#if state.atBound}
<span>Max</span>
{:else}
<PlusIcon aria-hidden="true" />
{/if}
{/snippet}
</NumberInputIncrement>
</NumberInputGroup>
</NumberInput>
</Field>每个部件的状态列在状态下。
样式
把组样式化为字段的盒子,并给里面的输入框和步进按钮设置样式。步进按钮上的 data-disabled 也表示它已到达边界,拖动改变值时 data-scrubbing 标记每个部件。在 Field 内部,原生输入框会收到 data-invalid 这样的校验属性。使用逻辑间距,让布局跟随周围的方向。
每个部件都有一个 data-slot,比如 number-input-group,它的状态属性列在数据属性下。
数据属性
NumberInput
[data-slot="number-input"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
data-readonly | Present when read-only. |
data-required | Present when required. |
data-scrubbing | Present while a drag on the scrub area changes the value. |
NumberInputScrubArea
[data-slot="number-input-scrub-area"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
data-readonly | Present when read-only. |
data-required | Present when required. |
data-orientation | horizontalverticalWhich way to drag. |
data-scrubbing | Present while a drag on the scrub area changes the value. |
NumberInputScrubAreaCursor
[data-slot="number-input-scrub-area-cursor"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
data-readonly | Present when read-only. |
data-required | Present when required. |
data-scrubbing | Present while a drag on the scrub area changes the value. |
NumberInputGroup
[data-slot="number-input-group"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
data-readonly | Present when read-only. |
data-required | Present when required. |
data-scrubbing | Present while a drag on the scrub area changes the value. |
NumberInputDecrement
[data-slot="number-input-decrement"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when the button can't step: it or the field is disabled, the field is read-only, or the value is at min. |
data-readonly | Present when read-only. |
data-required | Present when required. |
data-at-bound | |
data-scrubbing | Present while a drag on the scrub area changes the value. |
NumberInputControl
[data-slot="number-input-control"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
data-readonly | Present when read-only. |
data-required | Present when required. |
data-scrubbing | Present while a drag on the scrub area changes the value. |
NumberInputIncrement
[data-slot="number-input-increment"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when the button can't step: it or the field is disabled, the field is read-only, or the value is at max. |
data-readonly | Present when read-only. |
data-required | Present when required. |
data-scrubbing | Present while a drag on the scrub area changes the value. |
API 参考
属性和回调与下面相同,都作为 Svelte props。value 可以用 bind:value 绑定。
NumberInput
value?number | null- The value, or null for an empty field. Pass it to control the field.
defaultValue?number | null- The value at first, when uncontrolled. A form reset returns to it.
onValueChange?((value: number | null, details: ChangeDetails<NumberInputValueChangeReason>) => void)- Runs when the value changes: as a typed number becomes valid, and on every step.
details.cancel()stops it. onValueCommit?((value: number | null, details: CommitDetails<NumberInputValueChangeReason>) => void)- Runs once an interaction that changed the value ends: typing is committed, a key or a button is released, or a scrub ends. For saving.
min?number- The lowest value. Typed values below it are raised to it when committed.
max?number- The highest value. Typed values above it are lowered to it when committed.
step?number- How far one step moves. Committed values snap to steps from
min, or from 0 without one. largeStep?number- How far Page Up, Page Down, and Shift with an arrow key, a button, the wheel or a scrub move.
smallStep?number- How far Alt (Option on a Mac) with an arrow key, the wheel or a scrub moves, for fine changes. Values it reaches snap to it rather than to
step. format?Intl.NumberFormatOptions- How the value shows:
Intl.NumberFormatoptions, like{ style: "currency", currency: "USD" }. Typing accepts the same format in the locale, and percents are fractions: 50% is 0.5. locale?string- The locale for formatting and reading typed numbers. Defaults to the page's
lang, or the browser's language without one, once the page is interactive. Server markup uses English until then, so it never disagrees with the client. wheel?boolean- Lets the mouse wheel step the value while the input has focus.
disabled?boolean- Disables it like a native control: it can't be focused or changed, and isn't submitted.
readOnly?boolean- Keeps it focusable and submitted, but stops changes.
required?boolean- Blocks form submission while it's empty, with the browser's own message.
name?string- The name it submits under. The number is submitted as is, like
1234.5, never formatted. form?string- The id of a form to belong to, when it isn't inside that form.
controller?object- Steps it from anywhere. Create one with
createNumberInputController(). debug?boolean- Logs every state change with its reason to the console, in development builds.
NumberInputScrubArea
orientation?"horizontal" | "vertical"- Which way to drag: right and up increase.
pixelsPerStep?number- How far the pointer moves for one step, in CSS pixels.
controller?object- Connects a scrub area outside the number input, like an icon in a toolbar, to the number input with this controller. Inside it, it connects on its own. Web components use
for="<number input id>"instead.
NumberInputIncrement 和 NumberInputDecrement
disabled?boolean- Turns off this button alone. Pressing, clicking or holding it doesn't step.
状态
render 和 children snippet 会收到什么。每个部件都会收到字段的状态。
valuenumber | null- The value, or null when empty.
disabledboolean- Whether it's disabled, by itself or by a
<fieldset>. readOnlyboolean- Whether it's read-only: it stays focusable and submitted, but typing, steps and scrubs don't change it.
requiredboolean- Whether a form won't submit while it's empty.
scrubbingboolean- Whether a scrub is moving the value.
按钮的状态 NumberInputButtonState 说明该按钮能否步进,以及值是否到达它那一侧的边界,而不只是字段被禁用:
valuenumber | null- The value, or null when empty.
disabledboolean- Whether it's disabled, by itself or by a
<fieldset>. Whether the button can't step, because it or the field is disabled, the field is read-only, or the value is at its bound. readOnlyboolean- Whether it's read-only: it stays focusable and submitted, but typing, steps and scrubs don't change it.
requiredboolean- Whether a form won't submit while it's empty.
scrubbingboolean- Whether a scrub is moving the value.
atBoundboolean- Whether the value is at the bound this button steps toward, like the maximum for the increment.
原因
details.reason 说明值为什么变化。
input-changeEvent- Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
input-commitKeyboardEvent | FocusEvent- Enter, or leaving a number input, committed what was typed: a number input parses, clamps and snaps it to the step, and an autocomplete closes its suggestions on it.
step-keyKeyboardEvent- Arrow, Page Up, Page Down, Home or End stepped a slider or a number input.
increment-pressMouseEvent | PointerEvent- A number input's increment button was pressed, or held.
decrement-pressMouseEvent | PointerEvent- A number input's decrement button was pressed, or held.
wheelWheelEvent- The mouse wheel stepped a focused number input.
scrubPointerEvent- A drag on a number input's scrub area.
resetnone- A form reset.
restorenone- The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone- A controller or
apicall.
控制器
用 createNumberInputController() 创建一个,并作为 controller 传入。
每个写入方法都接受可选的 { reason, event },像一次按压那样运行变更回调,并在变更被取消时返回 false。
getValue()() => number | null- The value, or null when the field is empty.
setValue(value, options?)(value: number | null, options?: NumberInputChangeOptions | undefined) => boolean- Sets the value, as a user would. It's clamped and snapped to the step.
increment(options?)(options?: (NumberInputChangeOptions & { large?: boolean | undefined; }) | undefined) => boolean- Steps the value up, by
largeStepwith{ large: true }. decrement(options?)(options?: (NumberInputChangeOptions & { large?: boolean | undefined; }) | undefined) => boolean- Steps the value down, by
largeStepwith{ large: true }. focus()() => void- Moves focus to the input.
事件
回调先收到新值,然后收到详情。只有 onValueChange 没有取消变更时,绑定的 value 才会更新。
| 属性 | 所属 | 收到 |
|---|---|---|
bind:value | NumberInput | 值,为空时是 null |
onValueChange | NumberInput | (value, details):新值(为空时是 null)和原因 |
onValueCommit | NumberInput | (value, details):交互结束时的值和它的原因 |
无障碍
在原生文本输入框上遵循 WAI-ARIA spinbutton 模式的键盘模型,所以普通的文本编辑也能用。给输入框一个 FieldLabel 或 aria-label,并给两个步进按钮命名。每个按钮都用 aria-controls 指向输入框。
键盘
| 输入 | 增量 |
|---|---|
| ArrowUp、ArrowDown 或一个步进按钮 | step,默认是 1。 |
| Shift 加方向键或按钮;Page Up 或 Page Down | largeStep,默认十个步进。 |
| Alt(Option)加方向键 | smallStep,默认十分之一个步进。 |
| Home 或 End | 最小值或最大值,如果设置了。 |
Enter 提交输入的文字。步进按钮不在 Tab 顺序里,因为获得焦点的输入框可以通过方向键给出同样的步进。
经过测试的行为
下面每一行都是一个自动化测试。
- Starts with its default value, formatted.
- ArrowUp and ArrowDown step the value.
- Full-width digits from an input method commit as a number.
- Shift with an arrow key steps by the large step.
- Home and End go to the minimum and the maximum.
- Stepping stops at the bounds.
- Steps keep cents exact.
- The buttons aren't in the tab order.
- Typing a number changes the value.
- A typed value above the maximum is lowered when focus leaves.
- Typed text in the format is read and formatted when focus leaves.
- Typing sends change only once the text is committed.
- Letters can't be typed.
- Arrow keys step from what's typed.
- Text that isn't a number goes back to the value when focus leaves.
- The value commits when focus leaves.
- The increment and decrement buttons step the value.
- A button at its bound is disabled and marked data-at-bound.
- Holding a button repeats the step.
- A press commits when the button is released.
- A disabled button is marked disabled.
- A disabled button doesn't step when clicked or held, and the other still does.
- <button disabled> inside a step button element stays disabled past a bound. 仅在 Web components 运行。
- A button disabled while it's held stops repeating.
- Submits the number as is, not formatted.
- A disabled field can't be focused or changed.
- A read-only field can be focused, but not changed.
- A required empty field blocks the form.
- The mouse wheel does nothing unless turned on.
- The mouse wheel steps a focused field when turned on.
- A canceled change keeps the value.
- A controlled field follows its value.
- Reads and writes the locale's format.
运行于 React、Vue 和 web components。
模式之外:
- Page Up and Page Down step by the large step.
- A form reset returns every field to its default.
- A typed value snaps to the step when focus leaves.
- Enter commits and formats what's typed.
- Holding an arrow key commits once, when the key comes up.
- A field with cents asks for a decimal keypad.
- A scrub steps by distance, whatever the speed.
- A scrub that doesn't move commits nothing.
运行于 React、Vue 和 web components。
在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器记录:
- Announcements while moving to a number input with a keyboard.
运行于 React、Vue 和 web components。