我试图使用CSS来选择一些基于radio按钮状态的元素。
我想要做的是,如果选中了某个radio按钮,我想要下降几个级别,unhide是一个覆盖,这样用户就可以与禁用的radio按钮进行交互。
我知道您可以使用同级选择器(如~和> )来选择当前div的兄弟姐妹,但是如何选择checked单选按钮的父元素,然后遍历DOM以找到我想要的选择器?
我可以很容易地用JS来完成这个任务,但是如果可能的话,我更喜欢CSS。
这是一个CodePen
你可以看到我有四个radio按钮。其中有两处稍微缩进了。
我想要实现的是,如果有人选择Testing2 radio,我希望将包含opacity的.overlay设置为display: none。
我还需要维护相同的结构,而不需要重新组织HTML。
对我来说,使用同胞选择器是比较新的,所以在这种情况下,我可能没有正确地使用它们。
我试过:
#radio-1:checked ~ .overlay {
display: none;
}
#radio-1:checked > .radio-bump > .radio-group-2 ~ .overlay {
display: none;
}这是我的代码:
.overlay {
background: #fff;
z-index: 1;
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
opacity: 0.7;
}
.radio-group-2 {
position: relative;
}
.radio-bump {
margin-left: 20px;
}
#radio-1:checked ~ .overlay {
display: none;
}
#radio-1:checked > .radio-bump > .radio-group-2 ~ .overlay {
display: none;
}<div class="main-container">
<div class="shipping-container">
<div class="radio">
<input type="radio" id="radio" name="radio-group-1">
<label for="radio">Testing1</label>
</div>
<div class="radio-1">
<input type="radio" id="radio-1" name="radio-group-1">
<label for="radio-1">Testing2</label>
</div>
<div class="radio-bump">
<div class="radio-group-2">
<div class="overlay"></div>
<div class="radios">
<input type="radio" id="radio-2" name="radio-group-2">
<label for="radio-2">Testing3</label>
</div>
<div class="radios">
<input type="radio" id="radio-3" name="radio-group-2">
<label for="radio-3">Testing4</label>
</div>
</div>
</div>
</div>
</div>
发布于 2016-06-02 21:13:55
只有在从每个收音机/标签中移除容器时(使用纯CSS),这才是可能的。此外,您应该考虑使用指针事件而不是覆盖:
label:after { content: ""; display: block;}
.radio-group-2 {
margin-left: 20px;
opacity: .7;
pointer-events: none;
}
input:checked + label + .radio-group-2 {
opacity: 1;
pointer-events: all;
}<input type="radio" id="r-1" name="radio-group-1"><label for="r-1">Testing 1</label>
<input type="radio" id="r-2" name="radio-group-1"><label for="r-2">Testing 2</label>
<div class="radio-group-2">
<input type="radio" id="r-3" name="radio-group-2"><label for="r-3">Testing 3</label>
<input type="radio" id="r-4" name="radio-group-2"><label for="r-4">Testing 4</label>
</div>
注意相邻同级选择器的使用。
发布于 2016-06-02 21:23:40
考虑到你的情况
我还需要维护相同的结构,而不需要重新组织HTML。
那么对您的问题的答案是,如果这仅能用CSS实现,则是 no ,因为CSS没有父选择器,如果您可以重新组织HTML,那么CSS就能够通过使用相邻的选择器+或兄弟姐妹选择器~来实现这一点。
您有更多关于css中父选择器的问题相关信息。
发布于 2016-06-02 20:48:54
不幸的是,使用当前的HTML树无法在纯CSS中实现您在这里要求的内容。#radio1不能与.radio-bump位于同一个选择器中。
为了实现这一点,您需要将单选按钮元素放在DOM树的更高的位置。
要使它看起来像你想要的样子,你可以做的是把单选按钮放在树的更高的位置,但是要把标签保持在它所在的位置。然后使单选按钮元素display:none,并将一个:before或:after伪元素添加到标签中,样式为单选按钮。
一种类似的技术也用于创建纯CSS选项卡。
https://stackoverflow.com/questions/37601647
复制相似问题