首页 > 解决方案 > JavaScript DOM - 如何允许用户只选择一个选项

问题描述

我正在使用 HTML、CSS 和 JS DOM 制作石头、纸、剪刀游戏。我有 6 个按钮,可让您选择要玩的回合数。我想要它,这样当你点击其中一个时,它会变暗。然后,当您单击另一个时,那个会变暗,而前一个会恢复到较浅的颜色。有谁知道我将如何实现这一点?任何帮助将不胜感激 :)

// Changes button color when clicked
let rounds = document.querySelectorAll(".rounds");
rounds.forEach(i => {
    i.addEventListener("click", () => {
        i.style.cssText = "color: gray; border-color: gray";
    });
});
* {
  color: white;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: black;
  font-family: Arial, Helvetica, sans-serif;
}

#rounds {
  display: grid;
  justify-content: center;
  grid-template-columns: repeat(3, 0.2fr);
  grid-template-rows: repeat(2, 0.2fr);
  grid-gap: 10px;
  margin-top: 30px;
}

.rounds {
  background-color: black;
  font-size: 25px;
  border: solid 8px white;
  outline: none;
  padding: 5px 0;
}

.rounds:hover {
  cursor: pointer;
  color: lightgray;
  border-color: lightgray;
}
<div id="rounds">
    <button class="rounds">Best of 1</button>
    <button class="rounds">Best of 3</button>
    <button class="rounds">Best of 5</button>
    <button class="rounds">Best of 7</button>
    <button class="rounds">Best of 10</button>
    <button class="rounds">Custom</button>
  </div>

标签: javascripthtmlcss

解决方案


添加一个循环来还原所有其他按钮的颜色。

如果您为此使用类而不是分配cssText.

// Changes button color when clicked
let rounds = document.querySelectorAll(".rounds");
rounds.forEach(i =>
  i.addEventListener("click", () => {
    rounds.forEach(r => r.classList.remove("active"));
    i.classList.add("active");
  })
);
* {
  color: white;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: black;
  font-family: Arial, Helvetica, sans-serif;
}

#rounds {
  display: grid;
  justify-content: center;
  grid-template-columns: repeat(3, 0.2fr);
  grid-template-rows: repeat(2, 0.2fr);
  grid-gap: 10px;
  margin-top: 30px;
}

.rounds {
  background-color: black;
  font-size: 25px;
  border: solid 8px white;
  outline: none;
  padding: 5px 0;
}

.rounds:hover {
  cursor: pointer;
  color: lightgray;
  border-color: lightgray;
}

.rounds.active {
  color: gray;
  border-color: gray;
}
<div id="rounds">
  <button class="rounds">Best of 1</button>
  <button class="rounds">Best of 3</button>
  <button class="rounds">Best of 5</button>
  <button class="rounds">Best of 7</button>
  <button class="rounds">Best of 10</button>
  <button class="rounds">Custom</button>
</div>


推荐阅读