首页 > 解决方案 > 选中单选按钮时的样式元素

问题描述

初学者在这里!我有 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>

标签: javascripthtmlcss

解决方案


你的 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>


推荐阅读