You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义单选按钮选中样式异常:切换后旧项仍保留选中样式

解决自定义单选按钮切换时选中样式不清除的问题

你的问题出在JavaScript逻辑里——每次点击只给当前元素添加selected类,但没有移除其他元素的该类,导致所有点击过的元素都保留选中样式。以下是两种解决方案:

方案一:优化JavaScript逻辑

修改点击事件处理代码,每次点击时先清除所有.number元素的selected类,再给当前点击的元素添加该类:

const ratingState = document.querySelector(".rating-state");
const thanksState = document.querySelector(".thanks-state");
const btnSubmit = document.querySelector(".btn-submit");
const numberSelect = document.querySelectorAll(".number");

for (let i = 0; i < numberSelect.length; i++) {
  numberSelect[i].addEventListener("click", function () {
    // 先移除所有元素的selected类
    numberSelect.forEach(item => item.classList.remove("selected"));
    // 给当前点击的元素添加selected类
    this.classList.add("selected");
  });
}

方案二:纯CSS实现(更推荐)

利用原生单选按钮的:checked伪类结合:has()选择器,不需要JavaScript维护样式类,完全依赖原生表单状态同步样式,更简洁可靠:

修改后的CSS代码

.numbers-container {
  display: flex;
  gap: 1rem;
  justify-content: center;
  border: none;
}

input[type="radio"] {
  opacity: 0;
  position: fixed;
  width: 0;
}

.number {
  border-radius: 50%;
  height: 3rem;
  width: 3rem;
  display: flex;
  align-items: center;
  justify-content: center;
  color: hsl(217, 12%, 63%);
  background-color: hsl(213, 25%, 25%);
  border: none;
  cursor: pointer;
}

.number:hover {
  background-color: hsl(25, 97%, 53%);
  color: white;
}

/* 利用:has选择器匹配包含选中radio的.number */
.number:has(input[type="radio"]:checked) {
  background-color: hsl(217, 12%, 63%);
  color: white;
}

说明

  • 移除原来的.selected类定义,改用number:has(input[type="radio"]:checked)选择器,当内部的单选按钮被选中时,自动给父元素.number应用选中样式。
  • 不需要修改HTML和JavaScript(可删除原来点击事件中操作类的代码),完全依赖原生表单的单选特性同步样式,避免JS逻辑出错。

内容的提问来源于stack exchange,提问作者Miriam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:30:42