CSS-单选按钮样式在未选中时发生更改



在选择其他按钮后,是否可以更改尚未选择的单选按钮的样式?

因此,例如,当页面加载时,单选按钮的背景是黑色的。

当我单击选项1时,它的背景变为绿色。

当我单击选项1时,我希望选项2的背景也变为红色。

很抱歉,如果这个问题令人困惑,非常感谢!!

input {
background-color: black;
}
input:checked {
background-color: green;
}
<div>
<input type="radio" name="example">
<label>Option1</label>
</div>
<div>
<input type="radio" name="example">
<label>Option2</label>
</div>

你必须这样做。。

$(".radioElement").change(function(){
$(".input").addClass("inputSelectedRemoved");
if($(this).is(':checked')){
$(this).parent().addClass("inputSelected");
$(this).parent().removeClass("inputSelectedRemoved");
}   
});
.input {
background-color: black;
color:white;
}
.inputSelected{
background-color: green;
color:white;
}
.inputSelectedRemoved{
background-color: red;
color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input">
<input type="radio" name="example" value="Option 1" class="radioElement">
<label>Option1</label>
</div>
<div class="input">
<input type="radio" name="example" value="Option 2" class="radioElement">
<label>Option2</label>
</div>

只是为了好玩,为了表明它只能用CSS完成,这个例子会起作用,但我真的不建议这样做,只使用其中一个带有JS的解决方案。

由于您可以使用+访问下一个同级,或者使用~访问下一个子,因此您可以先定位所有单选按钮元素,然后再定位标签,这样您就可以以"下一个子"的身份访问标签。

使用CSS,您可以将标签定位在正确的位置,甚至为其提供覆盖单选按钮的背景:

.container{
position: relative;
display: flex;
flex-direction: column;
}
.container div{
width: 200px;
padding-left: 30px;
z-index: -1;
}
#in1:checked ~ #txt1{
background-color: green;
}
#in1:checked ~ #txt2{
background-color: red;
}
#in2:checked ~ #txt2{
background-color: green;
}
#in2:checked ~ #txt1{
background-color: red;
}
.container div{
background-color: black;
color: white;
}
#txt1 {
position: absolute;
left: 0;
top: 0;
}
#txt2 {
position: absolute;
left: 0;
top: 1em;
}
<div class="container">
<input id="in1" type="radio" name="example">
<input id="in2" type="radio" name="example">
<div id="txt1">Option 1</div>
<div id="txt2">Option 2</div>
</div>

我觉得是这样的:我添加了一个onclick属性

<div>
<input type="radio" name="example" onclick="document.body.style.backgroundColor = 'green'">
<label>Option1</label>
</div>
<div>
<input type="radio" name="example" onclick="document.body.style.backgroundColor = 'red'">
<label>Option2</label>
</div>

我希望这能帮助

最新更新