实现单选按钮选中时的背景与文字颜色切换
实现单选按钮选中时的样式切换
你可以通过CSS伪类或少量JS调整,实现按钮选中状态的样式切换,以下是具体方案:
方案一:纯CSS实现(推荐)
利用CSS的:has()伪类直接监听单选框的选中状态,无需修改JS代码:
.size-button { background-color: white; color: black; border: 1px solid black; margin-right: 20px; padding: 10px 30px; cursor: pointer; /* 可选:添加过渡动画让切换更平滑 */ transition: all 0.2s ease; /* 让按钮内部元素对齐更规整 */ display: inline-block; position: relative; } /* 隐藏原生单选框,让label完全充当按钮 */ .size-button input { position: absolute; opacity: 0; pointer-events: none; } /* 单选框选中时,修改label的样式 */ .size-button:has(input:checked) { background-color: black; color: white; }
方案二:兼容旧浏览器(JS辅助)
如果需要兼容不支持:has()的旧版浏览器,可通过JS给选中的按钮添加类名:
修改后的JS代码
function updateSelectedValue(optionName, selectedValue) { document.getElementById('selected-' + optionName).textContent = selectedValue; // 移除同组所有按钮的选中类 document.querySelectorAll('.size-button').forEach(btn => btn.classList.remove('selected')); // 给当前选中的按钮添加类 event.target.closest('.size-button').classList.add('selected'); }
补充CSS样式
.size-button.selected { background-color: black; color: white; }
两种方案都能实现你要的「选中时黑底白字」效果,可根据兼容性需求选择。
内容的提问来源于stack exchange,提问作者joejplant
相关产品推荐
相关产品推荐

