跳转到内容
按钮·免费

开关(Svelte)

Svelte 5 的开关组件,用带 role switch 的按钮实现,空格键、回车键和读屏软件都能正常使用。可以绑定 checked,也可以传入 onchange。支持可选的第二行说明、禁用状态,颜色来自 CSS 变量。

免费安装。

如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。

预览

ToggleSwitch.svelte · 138 行
<!--
  An on/off switch for Svelte 5 (runes + TypeScript). It is a real <button role="switch">:
  Space and Enter toggle it, and screen readers say its name and whether it is on.
  Bind the value, or listen to `onchange`:

    <ToggleSwitch label="Dark mode" bind:checked={dark} />
    <ToggleSwitch label="Sync over mobile data" checked={sync} onchange={(on) => save(on)} />

  Colours: --switch-on (the track when on), --switch-off, --switch-thumb, --switch-text.
-->
<script lang="ts">
  interface Props {
    label: string;
    checked?: boolean;
    disabled?: boolean;
    /** A second line under the label. */
    description?: string;
    onchange?: (checked: boolean) => void;
  }

  let { label, checked = $bindable(false), disabled = false, description, onchange }: Props = $props();

  const uid = $props.id();

  function toggle() {
    if (disabled) return;
    checked = !checked;
    onchange?.(checked);
  }
</script>

<div class="row">
  <span class="text">
    <span id="{uid}-label" class="label">{label}</span>
    {#if description}
      <span id="{uid}-description" class="description">{description}</span>
    {/if}
  </span>
  <button
    type="button"
    role="switch"
    aria-checked={checked}
    aria-labelledby="{uid}-label"
    aria-describedby={description ? `${uid}-description` : undefined}
    {disabled}
    onclick={toggle}
  >
    <span class="thumb" aria-hidden="true"></span>
  </button>
</div>

<style>
  .row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
    min-height: 48px;
    font-family: system-ui, sans-serif;
    color: var(--switch-text, #1d1f23);
  }

  .text {
    display: grid;
    gap: 0.15rem;
  }

  .label {
    font-weight: 500;
  }

  .description {
    font-size: 0.875rem;
    opacity: 0.75;
  }

  button {
    position: relative;
    flex: none;
    box-sizing: border-box;

此预览已截短。安装后可获得完整内容。

1.0.0 的变更

首个版本。

相关