自定义开关
轨道 + 滑块的开关,滑块滑过去就是「开」
全平台通用动效与背景内容区效果
实时预览(拖动参数,立刻看变化)
代码
<button class="switch" role="switch" aria-checked="false"
onclick="this.setAttribute('aria-checked', this.getAttribute('aria-checked') !== 'true')"></button>
<style>
.switch { width: 56px; height: 32px; border-radius: 999px; background: #d8d5cd; border: none;
position: relative; transition: background .25s; cursor: pointer; }
.switch::after { content: ""; position: absolute; top: 3.5px; left: 3.5px; width: 25px; height: 25px;
border-radius: 50%; background: #fff; box-shadow: 0 1px 4px rgba(0,0,0,.25);
transition: left .25s cubic-bezier(.22,1,.36,1); }
.switch[aria-checked="true"] { background: #141414; }
.switch[aria-checked="true"]::after { left: 27px; }
</style> <!-- 推荐用 button + 数据状态类,或直接用无样式原语(Radix Switch);纯 Tailwind 写法: -->
<button role="switch" aria-checked="true" class="relative h-8 w-14 rounded-full bg-neutral-900 transition-colors after:absolute after:left-[3.5px] after:top-[3.5px] after:h-[25px] after:w-[25px] after:rounded-full after:bg-white after:shadow after:transition-all aria-checked:after:left-[27px]"></button> export function Switch({ defaultChecked = false }) {
const [on, setOn] = React.useState(defaultChecked);
return (<button role="switch" aria-checked={on} onClick={() => setOn(!on)} style={{
width: 56, height: 32, borderRadius: 999, border: "none", cursor: "pointer", position: "relative",
background: on ? "#141414" : "#d8d5cd", transition: "background .25s" }}>
<span style={{ position: "absolute", top: 3.5, left: on ? 27 : 3.5, width: 25, height: 25, borderRadius: "50%",
background: "#fff", boxShadow: "0 1px 4px rgba(0,0,0,.25)", transition: "left .25s cubic-bezier(.22,1,.36,1)" }} />
</button>);
} 代码片段以 MIT 释出,可自由复制改用。
这个效果是怎么实现的
它是怎么工作的(中文)
本质是一个 role="switch" 的按钮:轨道是圆角长条,滑块是绝对定位的小圆,开状态时 left 从一头变到另一头配过渡。用 aria-checked 表达状态,屏幕阅读器才能读对。滑块要有阴影才看得出是「浮在轨道上」的可动件。
How it works (English)
At its core it's a button with role="switch": a pill track, an absolutely-positioned round thumb, and a left transition between ends. Use aria-checked for state so screen readers announce it correctly. A subtle shadow on the thumb sells it as a movable piece floating on the track.
参考与来源 Sources
本条为「批次 1(重建)」成果(2026-11-10 用户决定:原 妞妞老师 素材不导出,改由公开材料重建):效果概念参考开源效果生态——Magic UI(MIT)、Uiverse(MIT)、Animista、Paper Shaders(Apache-2.0)、tsParticles(MIT)、CSS Loaders(MIT)等(见 /resources 对应条目,许可以各项目为准);本站的实现代码、参数体系与全部文案均为 Aglaia 原创,未复制上述项目的代码或文案,也与 妞妞老师 原始素材无关。