javascript - 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>
解决方案
添加一个循环来还原所有其他按钮的颜色。
如果您为此使用类而不是分配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>
推荐阅读
- graph - CYPHER 存储 count() 值以供进一步使用
- omnet++ - 静脉:错误:无法解析主机/地址“sumo.dlr.de”
- ios - IOS Guess mime 类型
- extjs - sencha 多个过滤器在一个属性中
- windows - 是什么导致产生 Python 提示符?
- javascript - Laravel 中的 AJAX 调用 - 点赞按钮
- c# - 在 ASP.NET 中打开同一个网页时,如何显示不同的网页地址?
- c# - 在 OneDrive 或 iCloud 驱动器中存储 mdf 和 ldf sql 文件
- python - 复杂的变量赋值
- apache-spark - 通过大量字符串组合过滤数据