Checkbox
选择一个或多个选项,可以单独选,也可以成组选。
用复选框表示一个可以勾选或取消勾选的选项。几个选项属于同一个值时,用分组。
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<label data-slot="label">
<ui-checkbox>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
Accept terms and conditions
</label>
`
}
export { mount }安装
npm install @ui-sdk/web @ui-sdk/core导入组件来注册它的元素。这个 import 在服务器上是安全的。
import "@ui-sdk/web/checkbox"组合
用下面的组合构建一个 ui-checkbox:
ui-checkbox
└── ui-checkbox-indicator把复选框和它的文字包在一个 label 里。复选框已勾选或处于混合状态时,指示器会显示。
用法
导入部件并把它们组合起来:
<script type="module">
import "@ui-sdk/web/checkbox"
</script>
<label>
<ui-checkbox>
<ui-checkbox-indicator aria-hidden="true">✓</ui-checkbox-indicator>
</ui-checkbox>
Accept terms and conditions
</label>描述
选项需要更多说明时,用 ui-field-label 和 ui-field-description。字段会把标签和描述都连接到复选框。
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/field"
import { Check, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-checkbox>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
<div data-slot="stack">
<ui-field-label>Accept terms and conditions</ui-field-label>
<ui-field-description>
By clicking this checkbox, you agree to the terms and conditions.
</ui-field-description>
</div>
</ui-field>
`
}
export { mount }禁用
disabled 阻止聚焦和更改,并让复选框不参与表单提交。禁用的 fieldset 也一样。
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<label data-slot="label">
<ui-checkbox default-checked>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
Product updates
</label>
<label data-slot="label">
<ui-checkbox default-checked disabled>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
Security alerts
</label>
</div>
`
}
export { mount }只读
read-only 让复选框保持可聚焦并参与表单提交,同时阻止用户更改它。
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/field"
import { Check, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-checkbox name="two-factor" default-checked read-only>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
<div data-slot="stack">
<ui-field-label>Require two-factor authentication</ui-field-label>
<ui-field-description>
Your organization requires this setting.
</ui-field-description>
</div>
</ui-field>
`
}
export { mount }不确定
不确定的复选框表示一个部分勾选的集合。它有 aria-checked="mixed" 和 data-indeterminate。按压会勾选它;只有你的代码能把它放回混合状态。
从 default-checked="indeterminate" 开始,或把 "indeterminate" 作为受控值传入。指示器的 data-indeterminate 告诉它该显示哪个图标。父复选框会替你从分组推导这个状态。
<ui-checkbox default-checked="indeterminate">
<ui-checkbox-indicator aria-hidden="true">–</ui-checkbox-indicator>
</ui-checkbox>
<script type="module">
import "@ui-sdk/web/checkbox"
const indicator = document.querySelector("ui-checkbox-indicator")
new MutationObserver(() => {
indicator.textContent = indicator.hasAttribute("data-indeterminate")
? "–"
: "✓"
}).observe(indicator, { attributeFilter: ["data-indeterminate"] })
</script>受控
读取或设置元素的 checked property,并监听 checkedchange。它的 api property 是一个控制器,可以从任何地方更改它,比如下面的 Toggle 按钮。
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<button type="button">Toggle</button>
</div>
<label data-slot="label">
<ui-checkbox>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
Email me about product updates
</label>
</div>
`
const updates = root.querySelector("ui-checkbox")!
root
.querySelector("[data-slot=controls] button")!
.addEventListener("click", () => updates.api.toggle())
updates.addEventListener("checkedchange", (event) => {
const { value, reason } = event.detail
log(
root,
`${value === "indeterminate" ? "Mixed" : value ? "Checked" : "Unchecked"} (${reason})`
)
})
}
export { mount }表单
设置 name 和 value,让已勾选的复选框进入原生表单。未勾选和混合状态的复选框不提交任何内容。默认值是 "on"。独立的复选框可以共用一个 name 来提交多个值;应用还需要一份已勾选值的列表时,用分组。
required 会阻止提交,直到复选框被勾选。Reset 会把它恢复到 default-checked。把 form 设为表单的 id,就能从页面其他地方加入该表单。
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/field"
import { Check, createElement } from "lucide"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<form data-slot="stack">
<ui-field>
<ui-checkbox name="terms" value="yes" required>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
<div data-slot="stack">
<ui-field-label>Accept terms and conditions</ui-field-label>
<ui-field-description>You agree to our Terms of Service and Privacy Policy.</ui-field-description>
</div>
</ui-field>
<ui-field>
<ui-checkbox name="newsletter" value="weekly" default-checked>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
<div data-slot="stack">
<ui-field-label>Send me the weekly newsletter</ui-field-label>
<ui-field-description>Product news and tips, once a week. Unsubscribe anytime.</ui-field-description>
</div>
</ui-field>
<div data-slot="row">
<button type="submit">Create Account</button>
<button type="reset">Reset</button>
</div>
</form>
`
const form = root.querySelector("form")!
form.addEventListener("submit", (event) => {
event.preventDefault()
const entries = [...new FormData(form)].map(
([name, value]) => `${name}=${value}`
)
log(
root,
entries.length ? `Submitted ${entries.join("&")}` : "Submitted nothing"
)
})
}
export { mount }分组
ui-checkbox-group 维护一份已勾选值的列表。每个复选框提供它的 value;分组按复选框出现的顺序返回选中的值。用 aria-label、aria-labelledby 或 field 为分组命名。
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"
const toppings = [
{ value: "cheese", label: "Cheese" },
{ value: "mushrooms", label: "Mushrooms" },
{ value: "olives", label: "Olives" },
{ value: "peppers", label: "Peppers" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<h3 id="basic-toppings">Toppings</h3>
<ui-checkbox-group aria-labelledby="basic-toppings" default-value="cheese">
${toppings
.map(
(topping) => `
<label data-slot="label">
<ui-checkbox value="${topping.value}">
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
${topping.label}
</label>
`
)
.join("")}
</ui-checkbox-group>
</div>
`
}
export { mount }父复选框
添加一个带 parent 的复选框,用来勾选或取消勾选整个分组。所有值都选中时它处于勾选状态,一个都没有时处于未勾选状态,其余情况为混合状态。它用 aria-controls 指向子复选框,自身不提交任何内容。
把 all-values 传给分组,让父复选框在首次渲染时就有正确的状态,在服务器上也是如此。否则它要等复选框挂载后才能发现这些值。
import "@ui-sdk/web/checkbox"
import { Check, createElement, Minus } from "lucide"
const toppings = [
{ value: "cheese", label: "Cheese" },
{ value: "mushrooms", label: "Mushrooms" },
{ value: "olives", label: "Olives" },
{ value: "peppers", label: "Peppers" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<h3 id="parent-toppings">Toppings</h3>
<ui-checkbox-group
aria-labelledby="parent-toppings"
default-value="cheese,olives"
all-values="${toppings.map((topping) => topping.value).join(",")}"
>
<label data-slot="label">
<ui-checkbox parent>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
Select all
</label>
<div data-slot="stack">
${toppings
.map(
(topping) => `
<label data-slot="label">
<ui-checkbox value="${topping.value}">
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
${topping.label}
</label>
`
)
.join("")}
</div>
</ui-checkbox-group>
</div>
`
}
export { mount }禁用的分组
禁用分组可以锁定每个复选框,或者禁用一个子项,只固定那个值。父复选框只会更改启用的子项。
import "@ui-sdk/web/checkbox"
import { Check, createElement, Minus } from "lucide"
const backups = [
{ value: "photos", label: "Photos" },
{ value: "documents", label: "Documents" },
{ value: "messages", label: "Messages" },
]
const folders = [
{ value: "desktop", label: "Desktop", disabled: true },
{ value: "projects", label: "Projects", disabled: false },
{ value: "downloads", label: "Downloads", disabled: false },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="stack">
<h3 id="disabled-backups">Backups</h3>
<p data-slot="hint">Managed by your organization.</p>
<ui-checkbox-group aria-labelledby="disabled-backups" default-value="photos,documents" disabled>
${backups
.map(
(item) => `
<label data-slot="label">
<ui-checkbox value="${item.value}">
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
${item.label}
</label>
`
)
.join("")}
</ui-checkbox-group>
</div>
<div data-slot="stack">
<h3 id="disabled-folders">Sync folders</h3>
<ui-checkbox-group
aria-labelledby="disabled-folders"
default-value="desktop"
all-values="${folders.map((item) => item.value).join(",")}"
>
<label data-slot="label">
<ui-checkbox parent>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
Select all
</label>
<div data-slot="stack">
${folders
.map(
(item) => `
<label data-slot="label">
<ui-checkbox value="${item.value}"${item.disabled ? " disabled" : ""}>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
${item.label}
</label>
`
)
.join("")}
</div>
</ui-checkbox-group>
</div>
</div>
`
}
export { mount }受控的分组
读取或设置分组元素的 value property,并监听 valuechange。它的 api property 是一个控制器,可以替换这份列表,就像下面的 Select Weekdays 和 Clear 那样。
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"
import { log } from "./log"
const days = [
{ value: "mon", label: "Monday" },
{ value: "tue", label: "Tuesday" },
{ value: "wed", label: "Wednesday" },
{ value: "thu", label: "Thursday" },
{ value: "fri", label: "Friday" },
{ value: "sat", label: "Saturday" },
{ value: "sun", label: "Sunday" },
]
const weekdays = ["mon", "tue", "wed", "thu", "fri"]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<button type="button" data-action="weekdays">Select Weekdays</button>
<button type="button" data-action="clear">Clear</button>
</div>
<h3 id="controlled-days">Working days</h3>
<ui-checkbox-group aria-labelledby="controlled-days" default-value="mon,tue">
${days
.map(
(day) => `
<label data-slot="label">
<ui-checkbox value="${day.value}">
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
${day.label}
</label>
`
)
.join("")}
</ui-checkbox-group>
</div>
`
const schedule = root.querySelector("ui-checkbox-group")!
root
.querySelector('[data-action="weekdays"]')!
.addEventListener("click", () => schedule.api.setValue(weekdays))
root
.querySelector('[data-action="clear"]')!
.addEventListener("click", () => schedule.api.setValue([]))
schedule.addEventListener("valuechange", (event) => {
const { value, reason } = event.detail
const names = days
.filter((day) => value.includes(day.value))
.map((day) => day.label)
log(root, `${names.join(", ") || "No days"} (${reason})`)
})
}
export { mount }表单中的分组
在分组上设置 name,把每个已勾选的值都以该 name 提交。required 要求至少选择一项,Reset 会恢复 default-value。disabled 和 form 选项与单个复选框相同。
在字段中,字段提供分组的标签和描述,ui-field-error 会在选择让分组通过校验之前就地显示校验消息。表单与校验涵盖了共用的字段行为。
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/field"
import { Check, createElement } from "lucide"
import { log } from "./log"
const channels = [
{ value: "email", label: "Email" },
{ value: "sms", label: "SMS" },
{ value: "push", label: "Push notifications" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<form data-slot="stack">
<ui-field>
<ui-field-label>Notifications</ui-field-label>
<ui-field-description>Choose how we tell you about your orders.</ui-field-description>
<ui-checkbox-group name="notifications" required>
${channels
.map(
(channel) => `
<label data-slot="label">
<ui-checkbox value="${channel.value}">
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
${channel.label}
</label>
`
)
.join("")}
</ui-checkbox-group>
<div>
<ui-field-error>Choose at least one way to be notified.</ui-field-error>
</div>
</ui-field>
<button type="submit">Save</button>
</form>
`
const form = root.querySelector("form")!
form.addEventListener("submit", (event) => {
event.preventDefault()
const entries = [...new FormData(form)].map(
([name, value]) => `${name}=${value}`
)
log(root, `Saved ${entries.join("&")}`)
})
}
export { mount }表格
同一个父复选框可以从表格表头中选择行。每一行提供它的值和无障碍名称。
import "@ui-sdk/web/checkbox"
import { Check, createElement, Minus } from "lucide"
import { log } from "./log"
const people = [
{
id: "hollis",
name: "Hollis Grant",
email: "hollis@example.com",
role: "Owner",
},
{
id: "ines",
name: "Inès Moreau",
email: "ines@example.com",
role: "Editor",
},
{
id: "kofi",
name: "Kofi Mensah",
email: "kofi@example.com",
role: "Viewer",
},
{
id: "wren",
name: "Wren Takahashi",
email: "wren@example.com",
role: "Editor",
},
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-checkbox-group aria-label="Team members" default-value="hollis" all-values="${people.map((person) => person.id).join(",")}">
<table>
<caption data-slot="visually-hidden">Team members</caption>
<thead>
<tr>
<th>
<ui-checkbox aria-label="Select all" parent>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
${people
.map(
(person) => `
<tr>
<td>
<ui-checkbox value="${person.id}" aria-label="Select ${person.name}">
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
</td>
<td>${person.name}</td>
<td>${person.email}</td>
<td>${person.role}</td>
</tr>
`
)
.join("")}
</tbody>
</table>
</ui-checkbox-group>
`
root
.querySelector("ui-checkbox-group")!
.addEventListener("valuechange", (event) => {
log(root, `${event.detail.value.length} of ${people.length} selected`)
})
}
export { mount }动画
指示器出现时带有 data-starting-style,离开时带有 data-ending-style,并保持挂载直到退场结束。从这些状态过渡:
[data-slot="checkbox-indicator"] {
transition:
opacity 0.15s,
scale 0.15s;
&:is([data-starting-style], [data-ending-style]) {
opacity: 0;
scale: 0.5;
}
}keep-mounted 让指示器在未勾选时也留在页面中,并带有 data-unchecked,用于同时展示两种状态的样式。
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"
const tasks = [
{ label: "Write the release notes", done: false },
{ label: "Update the changelog", done: true },
{ label: "Tag the release", done: false },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
${tasks
.map(
(task) => `
<label data-slot="label">
<ui-checkbox${task.done ? " default-checked" : ""}>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
${task.label}
</label>
`
)
.join("")}
</div>
`
}
export { mount }自定义渲染
元素没有 render 函数。ui-checkbox 本身就是交互元素,所以把你的内容放在它里面,它的角色、标签和键盘行为就保持连接。用它的属性设置样式,并观察这些属性来改变里面的内容:这里每个复选框在 data-checked 改变时切换图标。
import "@ui-sdk/web/checkbox"
import { Check, createElement, Plus } from "lucide"
const topics = [
{ value: "design", label: "Design", checked: true },
{ value: "engineering", label: "Engineering", checked: false },
{ value: "marketing", label: "Marketing", checked: false },
{ value: "sales", label: "Sales", checked: false },
]
const icon = (checked: boolean) =>
createElement(checked ? Check : Plus, { "aria-hidden": "true" }).outerHTML
function mount(root: HTMLElement) {
root.innerHTML = `
<fieldset>
<legend>Topics you follow</legend>
<div data-slot="row">
${topics
.map(
(topic) =>
`<ui-checkbox name="topics" value="${topic.value}"${topic.checked ? " default-checked" : ""}>${icon(topic.checked)}${topic.label}</ui-checkbox>`
)
.join("")}
</div>
</fieldset>
`
const update = (checkbox: Element) => {
checkbox.querySelector("svg")!.outerHTML = icon(
checkbox.hasAttribute("data-checked")
)
}
new MutationObserver((records) =>
records.forEach((record) => update(record.target as Element))
).observe(root, { subtree: true, attributeFilter: ["data-checked"] })
root.querySelectorAll("ui-checkbox").forEach(update)
}
export { mount }样式
用 data-checked、data-unchecked 和 data-indeterminate 表示勾选状态,用 data-disabled、data-readonly 和 data-required 表示其余状态。指示器会得到与它的复选框相同的状态属性。
每个部件都有一个 data-slot,比如 checkbox,它的状态属性列在数据属性下。
数据属性
<ui-checkbox>
[data-slot="checkbox"]
| 属性 | 含义 |
|---|---|
data-checked | Present while checked. |
data-disabled | Present when disabled, by its own prop, a group or a <fieldset>. |
data-readonly | Present when read-only. |
data-required | Present when required. |
data-unchecked | Present while unchecked. |
data-indeterminate | Present while indeterminate. |
<ui-checkbox-indicator>
[data-slot="checkbox-indicator"]
| 属性 | 含义 |
|---|---|
data-checked | Present while checked. |
data-disabled | Present when disabled, by its own prop, a group or a <fieldset>. |
data-readonly | Present when read-only. |
data-required | Present when required. |
data-unchecked | Present while unchecked. |
data-indeterminate | Present while indeterminate. |
data-starting-style | Present for the indicator's first frame. Style the state you animate from. |
data-ending-style | Present while the indicator animates out. Style the state you animate to. |
<ui-checkbox-group>
[data-slot="checkbox-group"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when the group is disabled, by its own prop or a <fieldset>. |
data-required | Present when at least one checkbox must be checked. |
API 参考
props 是以 kebab case 写成的属性,比如 default-checked、read-only 和 all-values:"false" 表示
false,分组的 value、default-value 和 all-values 接受逗号分隔的值。checked 和
value 是实时的 property 和属性。回调是 DOM 事件。
Checkbox
checked?CheckedState- Whether it's checked. Pass it to control the checkbox.
defaultChecked?CheckedState- Whether it's checked at first, when uncontrolled. A form reset returns to it.
checkedchange event- Runs when a user or a form reset wants to change it.
details.reasonsays why, anddetails.cancel()stops it. 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 until it's checked, with the browser's own message.
name?string- The name it submits under. Without one, it submits nothing.
value?string- What it submits while checked.
form?string- The id of a form to belong to, when it isn't inside that form.
controller?{ toggle: (details?: Details) => boolean; getChecked: () => CheckedState; setChecked: (checked: CheckedState, details?: Details) => boolean; focus: () => void; }- Toggles it from anywhere. Create one with
createCheckboxController(). parent?boolean- Makes it the parent of its group: it checks or unchecks every checkbox in the group, and shows checked, unchecked or indeterminate from them.
debug?boolean- Logs every state change with its reason to the console, in development builds.
CheckboxIndicator
keepMounted?boolean- Whether the indicator stays in the page while unchecked, so it can be styled or animated in both states.
CheckboxGroup
value?T[]- The checked checkboxes' values. Pass it to control the group.
defaultValue?T[]- The values checked at first, when uncontrolled. A form reset returns to them.
valuechange event- Runs when a user or a form reset wants to change the value.
details.reasonsays why, anddetails.cancel()stops it. allValues?T[]- Every value a parent checkbox checks. Without it, the parent checks the checkboxes in the group. Pass it to render the parent right on the server.
disabled?boolean- Disables every checkbox in the group, and leaves them out of the form.
readOnly?boolean- Makes every checkbox in the group read-only: focusable and submitted, but presses don't change it.
required?boolean- Blocks form submission until at least one checkbox is checked, with the browser's own message.
name?string- The name every checkbox in the group submits under.
form?string- The id of a form to belong to, when the group isn't inside that form.
controller?{ getValue: () => T[]; setValue: (value: T[], details?: Details) => boolean; focus: () => void; }- Checks values from anywhere. Create one with
createCheckboxGroupController(). debug?boolean- Logs every state change with its reason to the console, in development builds.
状态
相同的状态会以数据属性的形式显示在每个元素上。
checkedboolean- Whether it's checked. False while indeterminate.
indeterminateboolean- Whether it's
"indeterminate", for a partly checked group. A press makes it checked. disabledboolean- Whether it's disabled, by itself or by a
<fieldset>. readOnlyboolean- Whether it's read-only: it stays focusable and submitted, but presses don't change it.
requiredboolean- Whether a form won't submit until it's checked. Indeterminate doesn't count.
指示器收到相同的状态。
checkedboolean- Whether it's checked. False while indeterminate.
indeterminateboolean- Whether it's
"indeterminate", for a partly checked group. A press makes it checked. disabledboolean- Whether it's disabled, by itself or by a
<fieldset>. readOnlyboolean- Whether it's read-only: it stays focusable and submitted, but presses don't change it.
requiredboolean- Whether a form won't submit until it's checked. Indeterminate doesn't count.
分组:
valuestring[]- The checked values.
disabledboolean- Whether the group is disabled, by itself or by a
<fieldset>. readOnlyboolean- Whether the group is read-only: its checkboxes stay focusable and submitted, but presses don't change them.
requiredboolean- Whether a form won't submit until at least one of its checkboxes is checked.
原因
event.detail.reason 说明勾选状态为什么改变。
pressMouseEvent | KeyboardEvent- A single-element control was pressed: a checkbox, a switch or a toggle.
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.
对分组来说,它说明已勾选的值为什么改变。
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
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.
Checkbox 控制器
元素的 api property 有相同的方法。checked property 读取并设置状态。
每个写入方法都接受可选的 { reason, event },像按压一样触发变更事件,并在变更被取消时返回 false。
toggle(details?)(details?: CheckboxChangeOptions | undefined) => boolean- Checks it, or unchecks it. An indeterminate checkbox becomes checked.
getChecked()() => CheckedState- Whether it's checked:
true,falseor"indeterminate". setChecked(checked, details?)(checked: CheckedState, details?: CheckboxChangeOptions | undefined) => boolean- Sets whether it's checked, as a user would.
focus()() => void- Moves focus to it.
CheckboxGroup 控制器
元素的 api property 有相同的方法。value property 读取并设置已勾选的值。
它的写入方法与复选框控制器相同。
getValue()() => T[]- The checked values.
setValue(value, details?)(value: T[], details?: CheckboxGroupChangeOptions | undefined) => boolean- Sets the checked values, as a user would. A disabled group ignores it.
focus()() => void- Moves focus to the first enabled checkbox.
事件
事件在各自的元素上触发,不冒泡,新状态或新值在 event.detail.value 中,reason 和 event 在它旁边。调用 preventDefault() 会取消变更。
| 成员 | 所属部件 | 说明 |
|---|---|---|
checked property, attribute | ui-checkbox | 勾选状态。属性设置起始值,且是实时的 |
api property | ui-checkbox | 控制器 |
checkedchange event | ui-checkbox | detail: { value: checked, reason, event, source } |
value property, attribute | ui-checkbox-group | 已勾选的值。属性以逗号分隔,设置起始值,且是实时的 |
api property | ui-checkbox-group | 控制器 |
valuechange event | ui-checkbox-group | detail: { value, reason, event, source } |
无障碍
复选框遵循 WAI-ARIA 复选框模式,分组的父复选框遵循它的混合复选框示例。ui-checkbox 本身就是控件,带 checkbox 角色,并通过 ElementInternals 参与表单,没有隐藏的输入框。下面每一行都是一个自动化测试。
键盘
| Key | 作用 |
|---|---|
| Tab | 移动到下一个复选框 |
| Space | 勾选或取消勾选它,或勾选一个混合状态的复选框 |
| Enter | 提交它的表单 |
经过测试的行为
- Clicking toggles it.
- Clicking its label toggles it.
- Clicking a label around it toggles it once.
- Space toggles it.
- Enter submits the form and never toggles it.
- Tab moves through checkboxes in order.
- The indicator shows only while checked.
- A change can be cancelled.
- A controlled checkbox follows its value.
- A read-only checkbox can be focused but not changed.
- Exit keyframes keyed on data-unchecked play before the indicator unmounts.
- An infinite exit animation still unmounts the indicator.
运行于 React、Vue 和 web components。
分组和父复选框:
- The group is named by its label.
- Starts on its default value.
- Checking a checkbox adds its value to the group.
- Every checked value submits under the group's name, in order.
- A reset returns to the default value.
- A required group blocks submission until one is checked.
- Is mixed while some checkboxes are checked.
- Checks every checkbox from mixed, then unchecks them all.
- Is checked once every checkbox is.
- Submits nothing itself.
运行于 React、Vue 和 web components。
在表单中:
- The form submits every checked control's name and value.
- Unchecked controls submit nothing.
- A checkbox outside the form joins it with the form attribute.
- Required controls block submission.
- A form reset returns every control to its default.
- A reset returns to the default value, not to nothing.
- A disabled fieldset disables the controls inside it.
- A read-only control still submits.
- A user's change fires native input and change events on the form.
运行于 React、Vue 和 web components。
在模式基线之外:
- The first invalid control takes focus in document order.
- A later required field without an error part doesn't take focus from the first.
- Take part in the form with no hidden input. 仅在 Web components 运行。
- Report validity like native controls. 仅在 Web components 运行。
- Have live checked and value properties. 仅在 Web components 运行。
- Are named by their labels. 仅在 Web components 运行。
运行于 React、Vue 和 web components。
在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器录制:
- Announcements while checking boxes with a keyboard.
- Announcements while choosing a radio with a keyboard.
运行于 React、Vue 和 web components。