如何用JavaScript修改CSS实现单选按钮选中时对应父div背景变色
问题原因
你原有代码存在三处核心问题:
- 第二个单选按钮的
onclick传参错误,把container2写成了container3,点击第二个单选按钮会错误修改第三个容器的样式 - 赋值类名误用了
style属性,style用于设置内联样式,修改类名需要使用className属性 - 逻辑不完整:仅修改了当前触发事件的容器样式,没有同步重置其他未选中容器的样式
修正后的完整代码
<!DOCTYPE html> <html> <style> .stylingForCheckedRadioButton { color: white; background-color: blue; border-style: solid; border-width: thin; border-color: grey; margin-bottom: 7px; width: 10%; height: 50px; border-radius: 6px; } .stylingForUnCheckedRadioButton { color: black; background-color: white; border-style: groove; border-width: thin; border-color: #DCDCDC; margin-bottom: 7px; width: 10%; height: 50px; border-radius: 6px; } </style> <script type="text/javascript"> function checkValue() { // 获取所有同组单选按钮 const rbs = document.querySelectorAll('input[name="radiobutton"]'); for (const rb of rbs) { // 直接获取当前单选按钮的父容器 const parentContainer = rb.parentElement; // 根据选中状态切换样式类 if (rb.checked) { parentContainer.className = "stylingForCheckedRadioButton"; } else { parentContainer.className = "stylingForUnCheckedRadioButton"; } } }; </script> <body> <h1>My Radio Buttons</h1> <div class="stylingForUnCheckedRadioButton" id="container1"> <input id="radiobuttonId1" type="radio" value="radiobuttonId1" name="radiobutton" onclick="checkValue()"> <label for="radiobuttonId1">Radio button 1</label> </div> <div class="stylingForUnCheckedRadioButton" id="container2"> <input id="radiobuttonId2" type="radio" value="radiobuttonId2" name="radiobutton" onclick="checkValue()"> <label for="radiobuttonId2">Radio button 2</label> </div> <div class="stylingForUnCheckedRadioButton" id="container3"> <input id="radiobuttonId3" type="radio" value="radiobuttonId3" name="radiobutton" onclick="checkValue()"> <label for="radiobuttonId3">Radio button 3</label> </div> </body> </html>
更简洁的纯CSS实现(无需JS)
如果不需要兼容极旧版本浏览器,可以直接用CSS的:has()选择器实现相同效果,不需要编写任何JS代码:
<!DOCTYPE html> <html> <style> .radio-container { color: black; background-color: white; border-style: groove; border-width: thin; border-color: #DCDCDC; margin-bottom: 7px; width: 10%; height: 50px; border-radius: 6px; } /* 单选按钮选中时自动修改父容器样式 */ .radio-container:has(input:checked) { color: white; background-color: blue; border-style: solid; border-color: grey; } </style> <body> <h1>My Radio Buttons</h1> <div class="radio-container"> <input id="radiobuttonId1" type="radio" value="radiobuttonId1" name="radiobutton"> <label for="radiobuttonId1">Radio button 1</label> </div> <div class="radio-container"> <input id="radiobuttonId2" type="radio" value="radiobuttonId2" name="radiobutton"> <label for="radiobuttonId2">Radio button 2</label> </div> <div class="radio-container"> <input id="radiobuttonId3" type="radio" value="radiobuttonId3" name="radiobutton"> <label for="radiobuttonId3">Radio button 3</label> </div> </body> </html>
内容的提问来源于stack exchange,提问作者Marco
相关产品推荐
相关产品推荐

