Switch开关
开关用于打开或关闭某项设置,切换后立即生效。组件渲染为带有 role="switch" 的原生 <button>。
何时使用
- 用开关来打开或关闭某项设置,切换后立即生效,无需额外的保存或提交步骤。
- 如果选择只是被标记并稍后随表单提交,或用于从列表中选取条目,复选框更合适。
- 变更保存期间使用
loading;需要由父组件确认变更时使用函数绑定。
代码演示
Notifications are on no change yet
<script lang="ts">
import { Switch } from 'svelte-ant-design';
let on = $state(true);
let last = $state('no change yet');
</script>
<Switch
bind:checked={on}
aria-label="Notifications"
onchange={(checked) => (last = `onchange(${checked})`)}
/>
<span>Notifications are {on ? 'on' : 'off'}</span>
<span role="status">{last}</span>
<script lang="ts">
import { Button, Switch } from 'svelte-ant-design';
let disabled = $state(true);
</script>
<Switch checked {disabled} aria-label="Disabled and on" />
<Switch {disabled} aria-label="Disabled and off" />
<Button onclick={() => (disabled = !disabled)}>Toggle disabled</Button>
Nothing around the switches moves when you toggle them.
<script lang="ts">
import { Switch } from 'svelte-ant-design';
</script>
<!-- Plain text for the two states. -->
<Switch checked checkedChildren="On" unCheckedChildren="Off" aria-label="Power" />
<Switch checkedChildren="On" unCheckedChildren="Off" aria-label="Power, off" />
<!-- The texts differ in width, yet the switch keeps the width of the longer one. -->
<Switch checkedChildren="Happy" unCheckedChildren="Sad" aria-label="Mood" />
<!-- A snippet for icons and other markup. -->
{#snippet check()}
<svg viewBox="0 0 12 12" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2">
<path d="M2 6.5 5 9l5-6" />
</svg>
{/snippet}
{#snippet cross()}
<svg viewBox="0 0 12 12" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2">
<path d="m2.5 2.5 7 7m0-7-7 7" />
</svg>
{/snippet}
<Switch checked checkedChildren={check} unCheckedChildren={cross} aria-label="Approved" />
<Switch checkedChildren={check} unCheckedChildren={cross} aria-label="Approved, off" />
<Switch size="small" checked checkedChildren="On" unCheckedChildren="Off" aria-label="Small power" />
<span>Nothing around the switches moves when you toggle them.</span>
<script lang="ts">
import { Switch } from 'svelte-ant-design';
</script>
<Switch checked aria-label="Medium" />
<Switch checked size="medium" aria-label="Medium, explicit" />
<Switch checked size="small" aria-label="Small" />
<!-- `default` is an alias of `medium` for people coming from Ant Design Vue or NG-ZORRO. -->
<Switch checked size="default" aria-label="Default, same as medium" />
<script lang="ts">
import { Switch } from 'svelte-ant-design';
let on = $state(false);
let saving = $state(false);
function save() {
saving = true;
setTimeout(() => (saving = false), 2000);
}
</script>
<Switch bind:checked={on} loading={saving} onchange={save} aria-label="Auto-save" />
<Switch loading checked aria-label="Loading and on" />
<Switch loading aria-label="Loading and off" />
<Switch loading size="small" checked aria-label="Small, loading and on" />
disabled, refused 0 times
<script lang="ts">
import { Switch } from 'svelte-ant-design';
let agreed = $state(false);
let enabled = $state(false);
let locked = $state(false);
let refused = $state(0);
</script>
<label>
<input type="checkbox" bind:checked={agreed} />
I accept the terms
</label>
<!-- A function binding: the setter decides whether a change is accepted. -->
<Switch
aria-label="Enable the feature"
bind:checked={
() => enabled,
(next) => {
if (next && !agreed) {
refused++;
return;
}
enabled = next;
}
}
/>
<span role="status">{enabled ? 'enabled' : 'disabled'}, refused {refused} times</span>
<!-- preventDefault() in onclick cancels the toggle and onchange. -->
<Switch
bind:checked={locked}
aria-label="Lock the setting"
onclick={(event) => {
if (!agreed) event.preventDefault();
}}
/>
<script lang="ts">
import { Switch } from 'svelte-ant-design';
</script>
<!-- class goes to the root; classNames adds classes to the root, content and indicator parts. -->
<Switch
checked
aria-label="With classes"
class="spaced"
classNames={{ root: 'halo', indicator: 'handle-outline' }}
/>
<!-- styles are inline styles per part; custom properties work too. -->
<Switch
checked
aria-label="With styles"
styles={{
root: { '--ads-switch-track-on': '#237804', '--ads-switch-track-on-hover': '#135200' },
indicator: { 'box-shadow': '0 0 0 2px #fff' }
}}
/>
<!-- style is the inline style of the root; styles.root is written after it and wins. -->
<Switch
aria-label="With style"
style="outline: 2px dashed #8c8c8c; outline-offset: 2px"
styles={{ root: { opacity: 0.85 } }}
/>
<style>
:global(.spaced) {
margin-inline-end: 12px;
}
:global(.halo) {
box-shadow: 0 0 0 4px rgb(22 104 220 / 25%);
}
:global(.handle-outline) {
outline: 1px solid rgb(0 0 0 / 35%);
}
</style>
Bluetooth Needed for headphones
<script lang="ts">
import { Switch } from 'svelte-ant-design';
</script>
<!-- A label element: clicking the text toggles the switch. -->
<label for="wifi">Wi-Fi</label>
<Switch id="wifi" checked />
<!-- aria-label for a switch that has no visible text. -->
<Switch aria-label="Airplane mode" title="Airplane mode" />
<!-- aria-labelledby points at any element that holds the name. -->
<span id="bluetooth-name">Bluetooth</span>
<Switch aria-labelledby="bluetooth-name" aria-describedby="bluetooth-hint" />
<small id="bluetooth-hint">Needed for headphones</small>
API
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| checked | 开关是否开启。使用 bind:checked 双向绑定;直接传值则作为初始状态。 | boolean | false |
| onchange | 用户每次切换后调用一次,参数为新的值。父组件修改 checked 时不会调用,禁用与加载中也不会调用。 | (checked: boolean, event: MouseEvent) => void | — |
| onclick | 原生点击回调,在状态改变之前执行;调用 event.preventDefault() 可取消切换。禁用与加载中不会调用。 | (event: MouseEvent) => void | — |
| disabled | 原生 disabled:无法聚焦,忽略点击与按键。 | boolean | false |
| loading | 在滑块中显示加载图标并忽略触发操作。开关保持焦点,并带有 aria-busy 与 aria-disabled。 | boolean | false |
| size | 尺寸。default 为 medium 的兼容别名。 | 'medium' | 'small' | 'default' | 'medium' |
| checkedChildren | 开启时显示的内容:文字,或用于图标与标记的 snippet。对辅助技术隐藏。关闭时仍保持挂载,因此开关会保持较长内容的宽度(snippet 内请避免使用 id 和副作用)。 | string | Snippet | — |
| unCheckedChildren | 关闭时显示的内容:文字,或用于图标与标记的 snippet。对辅助技术隐藏。开启时仍保持挂载,因此开关会保持较长内容的宽度(snippet 内请避免使用 id 和副作用)。 | string | Snippet | — |
| classNames | 为 root、content 与 indicator(滑块)三个部分追加的类名,附加在组件自带类名之后。 | Partial<Record<'root' | 'content' | 'indicator', string>> | — |
| styles | 这些部分的内联样式。属性名使用 kebab-case 或自定义属性,数字原样输出(不会自动添加 px),优先于组件自身样式。 | Partial<Record<'root' | 'content' | 'indicator', Record<string, string | number>>> | — |
| class | 根元素附加的 CSS 类名。 | string | — |
| style | 根元素的内联样式;styles.root 写在其后。 | string | — |
| native attributes | 按钮的原生属性(id、title、tabindex、aria-*、data-* 及其他事件处理器)会透传到元素上。type、role 与 aria-checked 由组件管理;加载状态优先于使用方传入的 aria-busy 与 aria-disabled。 | HTMLAttributes<HTMLButtonElement> | — |
与 Ant Design 的差异:
onclick 只接收事件(新的值请在 onchange 中读取);没有 defaultChecked、value、checkedValue 与 unCheckedValue,它们都由 bind:checked 替代。方法
| 方法 | 说明 | 类型 |
|---|---|---|
| focus | 让开关获得焦点。 | (options?: FocusOptions) => void |
| blur | 让开关失去焦点。 | () => void |
设计令牌
| 令牌 | 说明 | 默认值 |
|---|---|---|
| --ads-switch-height | 中号开关高度。 | 22px |
| --ads-switch-height-sm | 小号开关高度。 | 16px |
| --ads-switch-min-width | 中号开关最小宽度。 | 44px |
| --ads-switch-min-width-sm | 小号开关最小宽度。 | 28px |
| --ads-switch-handle-size | 中号开关滑块直径。 | 18px |
| --ads-switch-handle-size-sm | 小号开关滑块直径。 | 12px |
| --ads-switch-padding | 滑块与轨道边缘的间距。 | 2px |
| --ads-switch-content-margin-min | 文字远离滑块一侧的边距(中号)。 | 9px |
| --ads-switch-content-margin-max | 文字靠近滑块一侧的边距(中号)。 | 24px |
| --ads-switch-content-margin-min-sm | 小号开关的同一边距。 | 6px |
| --ads-switch-content-margin-max-sm | 小号开关的同一边距。 | 18px |
| --ads-switch-font-size | 中号开关文字大小。 | 12px |
| --ads-switch-font-size-sm | 小号开关文字大小。 | 10px |
| --ads-switch-spinner-border-width | 加载图标的线宽。 | 2px |
| --ads-switch-handle-shadow | 滑块阴影。 | 0 2px 4px 0 rgb(0 35 11 / 20%) |
| --ads-switch-loading-opacity | 加载中开关的不透明度。tokens-accessible.css 将其设为 1。 | 0.65 |
| --ads-switch-disabled-opacity | 禁用开关的不透明度。 | 0.4 |
| --ads-switch-track-off | 关闭时的轨道颜色。tokens-accessible.css 会将其加深为 #737373,以保证与页面背景 3:1 的对比度。 | rgba(0, 0, 0, 0.25) |
| --ads-switch-track-off-hover | 关闭时悬停的轨道颜色。 | rgba(0, 0, 0, 0.45) |
| --ads-switch-track-off-active | 关闭时按下的轨道颜色(与悬停相同)。 | rgba(0, 0, 0, 0.45) |
| --ads-switch-track-on | 开启时的轨道颜色。tokens-accessible.css 会将其加深为 #1668dc。 | #1677ff |
| --ads-switch-track-on-hover | 开启时悬停的轨道颜色。 | #4096ff |
| --ads-switch-track-on-active | 开启时按下的轨道颜色(与悬停相同)。 | #4096ff |
| --ads-switch-handle-bg | 滑块填充色。 | #ffffff |
| --ads-switch-content-color | 轨道内文字与图标的颜色。 | #ffffff |
无障碍
- 开关是带有
role="switch"与aria-checked的原生<button>。Enter 与 Space 可切换状态,方向键不起作用。 - 开关需要可访问名称:
aria-label、aria-labelledby或<label for>。开/关文字对辅助技术隐藏,因为作为名称它只会重复状态。 - 加载中的开关保持可聚焦,并带有
aria-busy与aria-disabled;点击、Enter 与 Space 均被忽略。禁用的开关使用原生 disabled。 - 默认颜色沿用 Ant Design,加载中的开关会变淡。引入
tokens-accessible.css后(深色主题则无需引入),轨道与滑块在所有状态下都保持至少 3:1 的对比度,文字则至少 4.5:1:关闭状态的轨道更深,加载中的开关也不会变淡。 - 在强制颜色模式(如 Windows 高对比度)下,开关使用系统颜色绘制:关闭时为描边轨道,开启时为填充轨道,禁用时使用系统的禁用色。