
通过将自定义切换控件重构为语义化 `
在 Web 可访问性(a11y)实践中,使用 +
✅ 正确方案:改用
✅ 推荐 HTML 结构(语义化 + 可访问)
⚠️ 注意:移除 和 ,不再依赖隐藏复选框;type="button" 防止表单意外提交。
✅ JavaScript 控制逻辑(简洁可靠)
const toggleBtn = document.getElementById("toggle");
const basic = document.getElementById("basic");
const professional = document.getElementById("professional");
const master = document.getElementById("master");
function toggleContent() {
const isPressed = toggleBtn.getAttribute("aria-pressed") === "true";
const newPressedState = !isPressed;
// 同步更新状态与 UI
toggleBtn.setAttribute("aria-pressed", newPressedState);
toggleBtn.setAttribute("aria-label",
newPressedState ? "切换为年付价格" : "切换为月付价格"
);
// 切换价格显示
if (newPressedState) {
basic.textContent = "19.99";
professional.textContent = "24.99";
master.textContent = "39.99";
} else {
basic.textContent = "199.99";
professional.textContent = "249.99";
master.textContent = "399.99";
}
}
// ✅ click 事件已天然兼容键盘(Enter/Space)+ 鼠标
toggleBtn.addEventListener("click", toggleContent);✅ CSS 样式示例(基于 aria-pressed 状态驱动)
#toggle {
background: #e0e7ff;
width: 4.4rem;
height: 2.4rem;
border: none;
border-radius: 2rem;
padding: 0;
cursor: pointer;
position: relative;
outline: none; /* 避免重复焦点环,可用 :focus-visible 替代 */
}
#toggle .toggle-inner {
position: absolute;
top: 0.2rem;
left: 0.2rem;
width: 2rem;
height: 2rem;
background: white;
border-radius: 50%;
transition: transform 0.25s ease;
}
#toggle[aria-pressed="true"] .toggle-inner {
transform: translateX(calc(100% - 0.4rem));
}
/* 增强键盘焦点可见性(推荐) */
#toggle:focus-visible {
outline: 2px solid #4f46e5;
outline-offset: 2px;
}✅ 关键优势总结
- ✅ 开箱即用键盘支持:Enter / Space 自动触发 click,无需 keydown 监听;
- ✅ 正确语义与无障碍:屏幕阅读器识别为“按钮”,播报 aria-label 和当前 aria-pressed 状态;
- ✅ 更少代码,更高可靠性:避免 tabindex + keydown 的复杂状态同步与浏览器兼容性陷阱;
- ✅ 符合 WCAG 2.1 AA 标准:满足 2.1.1 Keyboard、4.1.2 Name, Role, Value 等关键条款。
? 提示:若需保留原有复选框用于表单提交,应将其完全隐藏(display: none 或 aria-hidden="true")并放弃交互控制权,仅用










