【发布时间】:2021-06-07 10:39:17
【问题描述】:
这里是初学者!我有 3 个单选按钮,每个按钮都由一个容器包裹,当使用 JS 选择单选按钮时,我正在尝试设置容器的样式。 I was able to change the border style of the container when a radio button is selected, but wasn't able to remove that border style when the other buttons were selected.我怎样才能做到这一点?
const radioBtns = document.querySelectorAll('.radio-btn')
radioBtns.forEach((radioBtn, index) => {
const container = radioBtn.closest('.container');
radioBtn.addEventListener('click', () => {
container.classList.add('highlight');
if (!radioBtn.checked) {
container.classList.remove('highlight');
}
})
})
.container {
border: 1px solid black;
}
.container.highlight {
border: 1px solid green;
}
<div class=container>
<h1></h1>
<p></p>
<input type="radio" class="radio-btn">
</div>
<div class=container>
<h1></h1>
<p></p>
<input type="radio" class="radio-btn">
</div>
<div class=container>
<h1></h1>
<p></p>
<input type="radio" class="radio-btn">
</div>
【问题讨论】:
-
首先,您将单击侦听器添加到每个单选按钮,因此它们都将执行相同的操作。无论单击哪个单选按钮,只要其中一个,边框将始终存在,因为您无法“取消选择”单选按钮。为此,您需要一个复选框。或者,您可以将其设置为要赋予边框的单选按钮具有不同的单击侦听器。这就是我为你准备的一切。
-
另外,您可能希望在单击其他两个单选按钮时“取消选择”。如果是这种情况,您可以在 JS 中以编程方式执行此操作,然后将样式应用于其他框。
-
只需在您的无线电输入上添加相同的
name -
除了其他注释之外,您还需要指定属性
name并确保它们都相同(例如:name="car")。这将确保在任何时候都只能选择一个单选按钮。
标签: javascript html css