javascript - 选中单选按钮时的样式元素
问题描述
初学者在这里!我有 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 没问题...使用复选框。
那么为什么不使用复选框呢?嗬,因为你更喜欢圆形的收音机,对吧?然后将您的复选框设置为看起来像收音机!
在下面的代码片段中,我没有触及 HTML (执行更改复选框的单选)或 JS。
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;
position: relative;
}
.container.highlight {
border: 1px solid green;
background: rgba(0,255,0,0.3)
}
input[type='checkbox']:before{
position: absolute;
bottom: 2px;
left: 2px;
content: "";
border: 1px solid blue;
height: 15px;
width: 15px;
border-radius: 50%;
background: white;
}
input[type='checkbox']:checked:after{
position: absolute;
bottom: 6px;
left: 6px;
content: "";
height: 9px;
width: 9px;
border-radius: 50%;
background: blue;
}
<div class=container>
<h1></h1>
<p></p>
<input type="checkbox" class="radio-btn">
</div>
<div class=container>
<h1></h1>
<p></p>
<input type="checkbox" class="radio-btn">
</div>
<div class=container>
<h1></h1>
<p></p>
<input type="checkbox" class="radio-btn">
</div>
推荐阅读
- html - 从网页打印就像从 A4 的 PDF 文件打印一样
- java - 如何检查其他方法中的语句
- c# - 我们可以在不使用 CSS 的情况下添加“阅读更多”或“阅读更少”选项吗?
- c# - 处理从具有相同 IP 的多个客户端中的服务器接收值
- python - 如何在 Pandas 数据框中获取组中 B 列的最后一条记录和 A 列的总和?
- node.js - Openlayers 包 3.15.1 在构建时使用 v5.3.0 生成 ol.js 缩小文件
- angular - 将属性添加到表中,以便我可以在其上使用 css
- powershell - Exchange 获取最后一个活动不早于的活动邮箱
- c++ - 如何从窗口中删除 TOPMOST 属性
- reactjs - 如何使用预定义的数组初始化一个空的对象数组?