自定义Radio选中状态背景色修改为蓝色的技术实现问题
解决自定义Radio选中状态背景色不生效的问题
你的问题出在CSS选择器目标错误:你给被选中的<input>元素设置了背景色,但这个input已经被display: none隐藏,完全看不到效果。我们需要给包含选中input的<label>元素设置背景色。
方案1:使用CSS :has伪类(现代浏览器支持)
通过:has伪类判断label内的input是否被选中,直接修改label的样式:
.custom-radio label { color: #FFF; border-radius: 20px; display: inline-block; width: 60px; padding: 5px; font-size: 10pt; font-family: arial; background-color: gray; transition: all 0.3s; } .custom-radio input[type="radio"] { display: none; } /* 修改后的选择器,针对包含选中input的label */ .custom-radio label:has(input[type="radio"]:checked) { background-color: blue; }
方案2:利用Bootstrap自动添加的.active类(适配旧浏览器)
你用了data-toggle="buttons"和btn-group,Bootstrap会自动给被选中的label添加.active类,直接针对这个类写样式即可:
.custom-radio label { color: #FFF; border-radius: 20px; display: inline-block; width: 60px; padding: 5px; font-size: 10pt; font-family: arial; background-color: gray; transition: all 0.3s; } .custom-radio input[type="radio"] { display: none; } /* 针对Bootstrap自动添加的.active类 */ .custom-radio label.active { background-color: blue; }
两种方案都能实现:当radio被选中时,对应label的背景色变为蓝色,同时保留原有过渡动画效果。
内容的提问来源于stack exchange,提问作者sami salaam
相关产品推荐
相关产品推荐

