Botón·Gratis
Interruptor (Svelte)
Un interruptor de encendido y apagado para Svelte 5 hecho con un botón con role switch, así que Espacio, Intro y los lectores de pantalla funcionan. Enlaza checked o pasa onchange. Tiene una segunda línea opcional, estado desactivado y colores en variables CSS.
Se instala gratis.
Si tienes PocketCode instalado en tu Android, esto abre la página en la app.
Vista previa
ToggleSwitch.svelte · 138 líneas
<!--
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;Esta vista previa está recortada. El contenido completo llega al instalarlo.
Cambios en la 1.0.0
Primera versión.