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

如何仅用HTML和CSS实现多组判断题按钮独立选中效果

问题根因

你当前的实现依赖button的:focus伪类实现选中样式,而页面全局同一时间只能存在一个聚焦元素,因此切换题目选择时会丢失上一题的选中状态,只能全局保留一个选中效果。

修复方案

改用原生单选框<input type="radio">配合<label>实现,同name属性的单选框在单题内互斥选择,不同name的题目之间状态完全独立,无需引入JS即可满足需求。

修改后的CSS代码

/* 隐藏原生单选框 */
input[type="radio"] {
  display: none;
}

/* 把原按钮样式应用到label */
.answer-btn {
  background-color: #FFFFFF;
  border: 2px solid #222222;
  border-radius: 8px;
  box-sizing: border-box;
  color: #222222;
  cursor: pointer;
  display: inline-block;
  font-size: 16px;
  padding: 5px 18px;
  position: relative;
  text-align: center;
  touch-action: manipulation;
  transition: box-shadow .2s,-ms-transform .1s,-webkit-transform .1s,transform .1s;
}

.answer-btn:active {
  background-color: #F7F7F7;
  border-color: #000000;
  transform: scale(.90);
}

/* 选中正确选项的样式 */
input[type="radio"][value="1"]:checked + .answer-btn {
  background-color: green;
}

/* 选中错误选项的样式 */
input[type="radio"][value="0"]:checked + .answer-btn {
  background-color: red;
}

修改后的HTML代码

<!DOCTYPE html>
<html lang="fr">
<head>
  <link rel="stylesheet" href="json.css">
</head>
<body>
  <p>第1题题干</p>
  <input type="radio" name="q1" id="q1t" value="1">
  <label for="q1t" class="answer-btn">True</label>
  <input type="radio" name="q1" id="q1f" value="0">
  <label for="q1f" class="answer-btn">False</label>

  <p>第2题题干</p>
  <input type="radio" name="q2" id="q2t" value="1">
  <label for="q2t" class="answer-btn">True</label>
  <input type="radio" name="q2" id="q2f" value="0">
  <label for="q2f" class="answer-btn">False</label>

  <p>第3题题干</p>
  <input type="radio" name="q3" id="q3t" value="1">
  <label for="q3t" class="answer-btn">True</label>
  <input type="radio" name="q3" id="q3f" value="0">
  <label for="q3f" class="answer-btn">False</label>

  <p>第4题题干</p>
  <input type="radio" name="q4" id="q4t" value="1">
  <label for="q4t" class="answer-btn">True</label>
  <input type="radio" name="q4" id="q4f" value="0">
  <label for="q4f" class="answer-btn">False</label>

  <p>第5题题干</p>
  <input type="radio" name="q5" id="q5t" value="1">
  <label for="q5t" class="answer-btn">True</label>
  <input type="radio" name="q5" id="q5f" value="0">
  <label for="q5f" class="answer-btn">False</label>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:45:04