Checkbox多选框
多选框用于把某个值标记为已选,选择通常稍后随表单提交。组件在 <label> 中渲染原生 <input type="checkbox">;CheckboxGroup 用于管理一组多选框。
何时使用
- 用多选框从列表中选取一项或多项,或标记一个稍后随表单提交的选择。
- 如果变更立即生效,无需额外的保存或提交步骤,开关更合适。
- “全选”控件请结合
indeterminate与组使用;需要由父组件确认变更时使用函数绑定。
代码演示
The box is checked no change yet
<script lang="ts">
import { Checkbox } from 'svelte-ant-design';
let remember = $state(true);
let last = $state('no change yet');
</script>
<!-- The text between the tags is the children of the checkbox, and its accessible name. -->
<Checkbox bind:checked={remember} onchange={(checked) => (last = `onchange(${checked})`)}>
Remember me
</Checkbox>
<span>The box is {remember ? 'checked' : 'unchecked'}</span>
<span role="status">{last}</span>
<script lang="ts">
import { Button, Checkbox } from 'svelte-ant-design';
let disabled = $state(true);
</script>
<Checkbox {disabled}>Unchecked</Checkbox>
<Checkbox {disabled} checked>Checked</Checkbox>
<Checkbox {disabled} indeterminate>Indeterminate</Checkbox>
<Button onclick={() => (disabled = !disabled)}>Toggle disabled</Button>
disabled, refused 0 times
<script lang="ts">
import { Checkbox } from 'svelte-ant-design';
let agreed = $state(false);
let enabled = $state(false);
let locked = $state(false);
let refused = $state(0);
</script>
<Checkbox bind:checked={agreed}>I accept the terms</Checkbox>
<!-- A function binding: the setter decides whether a change is accepted. -->
<Checkbox
bind:checked={
() => enabled,
(next) => {
if (next && !agreed) {
refused++;
return;
}
enabled = next;
}
}
>
Enable the feature
</Checkbox>
<span role="status">{enabled ? 'enabled' : 'disabled'}, refused {refused} times</span>
<!-- preventDefault() in a forwarded onclick cancels the toggle and onchange. -->
<Checkbox
bind:checked={locked}
onclick={(event) => {
if (!agreed) event.preventDefault();
}}
>
Lock the setting
</Checkbox>
Selected: Apple
<script lang="ts">
import { Checkbox, CheckboxGroup } from 'svelte-ant-design';
const options = ['Apple', 'Pear', 'Orange'];
let selected = $state<string[]>(['Apple']);
const all = $derived(selected.length === options.length);
const some = $derived(selected.length > 0 && !all);
</script>
<!-- indeterminate only changes the look; checked stays the value that is reported. -->
<Checkbox
checked={all}
indeterminate={some}
onchange={(checked) => (selected = checked ? [...options] : [])}
>
Check all
</Checkbox>
<CheckboxGroup bind:value={selected} {options} aria-label="Fruits" />
<span role="status">Selected: {selected.join(', ') || 'nothing'}</span>
no change yet
<script lang="ts">
import { CheckboxGroup } from 'svelte-ant-design';
let fruits = $state<string[]>(['Apple']);
let sizes = $state<number[]>([2]);
let extras = $state<string[]>([]);
let last = $state('no change yet');
</script>
<!-- Strings and numbers are both the value and the label; the group reports the whole array. -->
<CheckboxGroup
bind:value={fruits}
options={['Apple', 'Pear', 'Orange']}
aria-label="Fruits"
onchange={(value) => (last = `onchange([${value.join(', ')}])`)}
/>
<CheckboxGroup bind:value={sizes} options={[1, 2, 3]} aria-label="Sizes" name="size" />
<!-- Objects add a snippet label, disabled, title and an onchange of the option. -->
{#snippet cherry()}<strong>Cherry</strong>{/snippet}
<CheckboxGroup
bind:value={extras}
aria-label="Extras"
options={[
{ label: cherry, value: 'cherry' },
{
label: 'Pear',
value: 'pear',
title: 'Juicy',
onchange: (checked) => (last = `pear: ${checked}`)
},
{ label: 'Plum', value: 'plum', disabled: true }
]}
/>
<!-- disabled disables the whole group. -->
<CheckboxGroup disabled value={['Apple']} options={['Apple', 'Pear']} aria-label="Disabled fruits" />
<span role="status">{last}</span>
<script lang="ts">
import { Checkbox, CheckboxGroup } from 'svelte-ant-design';
let days = $state<string[]>(['mon', 'wed']);
</script>
<!-- The children of the group are your own markup: here a grid. Each checkbox needs a value. -->
<CheckboxGroup bind:value={days} aria-label="Days" style="display: block; width: 100%">
<div class="grid">
<Checkbox value="mon">Monday</Checkbox>
<Checkbox value="tue">Tuesday</Checkbox>
<Checkbox value="wed">Wednesday</Checkbox>
<Checkbox value="thu">Thursday</Checkbox>
<Checkbox value="fri" disabled>Friday (closed)</Checkbox>
<Checkbox value="sat">Saturday</Checkbox>
</div>
</CheckboxGroup>
<span role="status">Selected: {days.join(', ') || 'nothing'}</span>
<style>
.grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px 16px;
}
</style>
<script lang="ts">
import { Checkbox, CheckboxGroup } from 'svelte-ant-design';
</script>
<!-- class goes to the root; classNames adds classes to the root, icon and label parts. -->
<Checkbox checked class="spaced" classNames={{ root: 'halo', label: 'strong' }}>With classes</Checkbox>
<!-- styles are inline styles per part; custom properties work too. -->
<Checkbox
checked
styles={{
root: { '--ads-checkbox-checked-bg': '#237804', '--ads-checkbox-checked-bg-hover': '#135200' },
icon: { 'border-radius': '50%' },
label: { 'font-weight': 600 }
}}
>
With styles
</Checkbox>
<!-- style is the inline style of the root; styles.root is written after it and wins. -->
<Checkbox style="outline: 2px dashed #8c8c8c; outline-offset: 2px" styles={{ root: { opacity: 0.85 } }}>
With style
</Checkbox>
<!-- A group: root, and item, itemIcon and itemLabel for every checkbox inside. -->
<CheckboxGroup
value={['a']}
options={['a', 'b']}
aria-label="Group parts"
class="boxed"
classNames={{ root: 'halo', item: 'item' }}
styles={{ itemIcon: { 'border-radius': '50%' }, itemLabel: { 'font-style': 'italic' } }}
style="padding: 4px 8px"
/>
<style>
:global(.spaced) {
margin-inline-end: 12px;
}
:global(.halo) {
box-shadow: 0 0 0 4px rgb(22 104 220 / 25%);
border-radius: 4px;
}
:global(.strong) {
text-decoration: underline;
}
:global(.boxed) {
border: 1px dashed #8c8c8c;
}
:global(.item) {
padding-inline: 4px;
}
</style>
Bluetooth Needed for headphones
<script lang="ts">
import { Checkbox } from 'svelte-ant-design';
</script>
<!-- The text between the tags names the checkbox, and a click on it toggles the box. -->
<Checkbox>Wi-Fi</Checkbox>
<!-- aria-label for a checkbox that has no visible text. -->
<Checkbox aria-label="Airplane mode" title="Airplane mode" />
<!-- aria-labelledby points at any element that holds the name. -->
<span id="bluetooth-name">Bluetooth</span>
<Checkbox aria-labelledby="bluetooth-name" aria-describedby="bluetooth-hint" />
<small id="bluetooth-hint">Needed for headphones</small>
<!-- An external label: the id of the checkbox goes to its input. -->
<label for="sound">Sound</label>
<Checkbox id="sound" checked />
<script lang="ts">
import { Button, Checkbox, CheckboxGroup } from 'svelte-ant-design';
let terms = $state(false);
let topics = $state<string[]>([]);
let result = $state('');
function submit(event: SubmitEvent) {
event.preventDefault();
const data = new FormData(event.currentTarget as HTMLFormElement);
result = `Submitted: ${JSON.stringify([...data.entries()])}`;
}
// A native reset does not change the state of the components: reset it here.
function reset() {
terms = false;
topics = [];
result = '';
}
</script>
<form onsubmit={submit} onreset={reset}>
<Checkbox bind:checked={terms} name="terms" value="accepted" required>I accept the terms</Checkbox>
<CheckboxGroup bind:value={topics} name="topic" options={['news', 'offers']} aria-label="Topics" />
<Button htmlType="submit" type="primary">Save</Button>
<Button htmlType="reset">Reset</Button>
</form>
<span role="status">{result}</span>
API
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| checked | 多选框是否选中。使用 bind:checked 双向绑定;直接传值则作为初始状态。在 CheckboxGroup 内状态来自组的 value,此属性会被忽略。 | boolean | false |
| indeterminate | “全选”控件的“部分选中”外观。只改变外观和读屏状态(混合);对外报告和提交的值仍是 checked。 | boolean | false |
| disabled | input 的原生 disabled:无法聚焦,忽略点击与按键。组的 disabled 同样生效。 | boolean | false |
| value | 在 CheckboxGroup 中的标识,也是 input 的原生 value(数字会以文本写入)。未设置时 input 保持原生的 on。 | string | number | — |
| name | input 的原生 name。在组内以组的 name 为准。 | string | — |
| children | 标签:任意标记,也是可访问名称;没有它时请提供 aria-label、aria-labelledby 或外部 <label for>。 | Snippet | — |
| onchange | 用户每次切换、状态改变后调用一次,参数为新的值和原生 change 事件(event.target 即 input)。父组件修改 checked 时不会调用,禁用时也不会调用。 | (checked: boolean, event: Event) => void | — |
| classNames | 为 root(label)、icon(方框)与 label(文字)三个部分追加的类名,附加在组件自带类名之后。 | Partial<Record<'root' | 'icon' | 'label', string>> | — |
| styles | 这些部分的内联样式。属性名使用 kebab-case 或自定义属性,数字原样输出(不会自动添加 px),优先于组件自身样式。 | Partial<Record<'root' | 'icon' | 'label', Record<string, string | number>>> | — |
| class | 根元素附加的 CSS 类名。 | string | — |
| style | 根元素的内联样式;styles.root 写在其后。 | string | — |
| title | 根 label 的原生 title,提示同时覆盖方框和文字。 | string | — |
| native attributes | input 的原生属性(id、required、form、tabindex、aria-*、data-*、onfocus、onblur、onclick 及其他事件处理器)会透传到元素上。type、checked、indeterminate、value、disabled 与 onchange 由组件管理。 | HTMLInputAttributes | — |
与 Ant Design 的差异:
onchange 接收 (checked, event) 与原生事件(React 传入的是带 target 的对象);没有 defaultChecked 与 defaultValue,它们由 bind:checked 与 bind:value 替代;组是独立的 CheckboxGroup 组件,其 onchange 接收 (value, event)。CheckboxGroup 的 API
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| value | 已选中的值。使用 bind:value 双向绑定;直接传值则作为初始选择。数组按选项(或标记中多选框)的顺序排列;不匹配任何项的值会保留在已知值之后。 | CheckboxValue[] | [] |
| options | 为每一项渲染一个多选框。字符串或数字既是值也是标签;对象为 { label, value, disabled?, title?, class?, style?, onchange? },其中 label 是文字或 snippet。值必须唯一。有内容时会忽略 children。 | ReadonlyArray<CheckboxValue | CheckboxOption> | [] |
| children | 自己的标记,内部任意位置可放 Checkbox(网格、分栏)。每个都需要 value;非 production 环境下缺失会抛出错误。 | Snippet | — |
| disabled | 禁用组内所有多选框;选项自己的 disabled 只禁用该项。 | boolean | false |
| name | 组内每个 input 的原生 name;优先于多选框自己的 name。 | string | — |
| onchange | 用户每次切换时调用一次,参数为新的已选值数组和被切换 input 的 change 事件。多选框或选项自己的 onchange 先执行。父组件修改 value 时不会调用。 | (value: CheckboxValue[], event: Event) => void | — |
| classNames | 额外的类名:root 是组本身;item、itemIcon 与 itemLabel 会追加到组内每个多选框的 root、icon 与 label 部分。 | Partial<Record<'root' | 'item' | 'itemIcon' | 'itemLabel', string>> | — |
| styles | 这些部分的内联样式。多选框自己的 styles 写在组的样式之后,因此优先。 | Partial<Record<'root' | 'item' | 'itemIcon' | 'itemLabel', Record<string, string | number>>> | — |
| class | 根元素附加的 CSS 类名。 | string | — |
| style | 根元素的内联样式;styles.root 写在其后。 | string | — |
| native attributes | <div> 的原生属性(id、aria-label、aria-labelledby、aria-describedby、data-*、事件处理器)会透传到元素上。role="group" 由组件管理:请用 aria-label 或 aria-labelledby 为组命名。 | HTMLAttributes<HTMLDivElement> | — |
方法
| 方法 | 说明 | 类型 |
|---|---|---|
| focus | 让多选框获得焦点。 | (options?: FocusOptions) => void |
| blur | 让多选框失去焦点。 | () => void |
设计令牌
| 令牌 | 说明 | 默认值 |
|---|---|---|
| --ads-checkbox-size | 方框的宽高。 | 16px |
| --ads-checkbox-radius | 方框圆角半径。 | 4px |
| --ads-checkbox-border-width | 方框边框粗细。 | 1px |
| --ads-checkbox-check-width | 对勾的线宽。 | 2px |
| --ads-checkbox-font-size | 标签字号。 | 14px |
| --ads-checkbox-line-height | 标签行高;方框与第一行垂直居中。 | 1.5714 |
| --ads-checkbox-label-padding | 方框与文字之间的间距,文字两侧各一份。 | 8px |
| --ads-checkbox-group-gap | 组内多选框之间的间距。 | 8px |
| --ads-checkbox-bg | 未选中方框的填充色。 | #ffffff |
| --ads-checkbox-border | 未选中方框的边框色。tokens-accessible.css 会将其加深为 #737373,以保证与页面背景 3:1 的对比度。 | #d9d9d9 |
| --ads-checkbox-border-hover | 未选中或半选方框在悬停(方框或文字)时的边框色。 | #1677ff |
| --ads-checkbox-checked-bg | 选中方框的填充与边框色。 | #1677ff |
| --ads-checkbox-checked-bg-hover | 选中方框在悬停时的填充与边框色。tokens-accessible.css 会将其加深为 #0958d9(#4096ff 与页面背景的对比度为 2.99:1)。 | #4096ff |
| --ads-checkbox-check-color | 对勾的颜色。 | #ffffff |
| --ads-checkbox-indeterminate-color | 半选方框中横条的颜色。 | #1677ff |
| --ads-checkbox-disabled-bg | 禁用方框的填充色。 | rgba(0, 0, 0, 0.04) |
| --ads-checkbox-disabled-border | 禁用方框的边框色。 | #d9d9d9 |
| --ads-checkbox-disabled-check-color | 禁用方框中的对勾或横条颜色。 | rgba(0, 0, 0, 0.25) |
无障碍
- 多选框是
<label>中的原生<input type="checkbox">:Space 可切换,点击文字同样有效,并且会参与表单(name、value、required)。Enter 与方向键不起作用。 - 多选框需要可访问名称:自身文字(
children)、aria-label、aria-labelledby或外部<label for>。组带有role="group",请用aria-label或aria-labelledby为其命名。 indeterminate的多选框会被读屏软件播报为“混合”。它只改变外观和播报状态:对外报告和提交的值仍是checked。- 默认颜色沿用 Ant Design。引入
tokens-accessible.css后(深色主题则无需引入),边框、对勾、横条与焦点环在所有状态下都保持至少 3:1 的对比度,文字则至少 4.5:1:未选中的边框与悬停填充色更深。 - 在强制颜色模式(如 Windows 高对比度)下,半选状态的横条使用文字颜色绘制,因此仍可与未选中区分;禁用的多选框使用系统的禁用色。