如何在Blazor/Sass中实现选中输入框时自定义父元素样式?
单选框选中时自定义
我设置了一组<label>元素,每个元素内部包含一个<input type="radio">子元素,点击<label>即可选中对应的单选框,代码如下:
<div id="content"> <label class="option"> <input type="radio" name="letters" value="a" /> <a>A</a> <p>Lorem Ipsum.</p> </label> <label class="option"> <input type="radio" name="letters" value="b" /> <a>B</a> <p>Lorem Ipsum.</p> </label> <label class="option"> <input type="radio" name="letters" value="cS" /> <a>C</a> <p>Lorem Ipsum.</p> </label> <label class="option"> <input type="radio" name="letters" value="d" /> <a>D</a> <p>Lorem Ipsum.</p> </label> </div>
需要实现的效果:当单选框被选中时,修改对应<label>的背景颜色。
解决方案
方法一:使用CSS :has()选择器(现代浏览器推荐)
利用:has()选择器直接选中包含已选中单选框的<label>,写法简洁直观:
/* 默认label基础样式 */ .option { display: block; padding: 10px; margin: 5px 0; border: 1px solid #ddd; cursor: pointer; transition: background-color 0.2s; } /* 单选框选中时的label样式 */ .option:has(input[type="radio"]:checked) { background-color: #e6f7ff; border-color: #1890ff; } /* 可选:隐藏原生单选框,用自定义样式替代 */ .option input[type="radio"] { display: none; }
方法二:相邻兄弟选择器(兼容旧浏览器)
将单选框移到<label>外部,通过for属性关联,再用相邻兄弟选择器实现样式控制:
调整后的HTML:
<div id="content"> <input type="radio" name="letters" id="opt-a" value="a" /> <label class="option" for="opt-a"> <a>A</a> <p>Lorem Ipsum.</p> </label> <input type="radio" name="letters" id="opt-b" value="b" /> <label class="option" for="opt-b"> <a>B</a> <p>Lorem Ipsum.</p> </label> <input type="radio" name="letters" id="opt-c" value="cS" /> <label class="option" for="opt-c"> <a>C</a> <p>Lorem Ipsum.</p> </label> <input type="radio" name="letters" id="opt-d" value="d" /> <label class="option" for="opt-d"> <a>D</a> <p>Lorem Ipsum.</p> </label> </div>
对应的CSS:
.option { display: block; padding: 10px; margin: 5px 0; border: 1px solid #ddd; cursor: pointer; transition: background-color 0.2s; } input[type="radio"]:checked + .option { background-color: #e6f7ff; border-color: #1890ff; } input[type="radio"] { display: none; }
两种方法都能实现目标效果,可根据浏览器兼容性需求选择。
内容的提问来源于stack exchange,提问作者Pedro Costa
相关产品推荐
相关产品推荐

