我尝试使用 :checked 类显示和隐藏内容,但在嵌套的 UL LI 列表中似乎不起作用。请任何人指导我解决这个问题。看起来我犯了一些我看不到的错误。
div#content {
display:none;
}
#show:checked ~ div#content{
display:block;
}
<ul>
<li>
<input type=radio id="show" name="group">
<label for="show">Show</label>
</li>
<li>
<input type=radio id="show1" name="group">
<label for="show1">Show</label>
</li>
<li>
<input type=radio id="show2" name="group">
<label for="show2">Show</label>
<li>
<input type=radio id="show3" name="group">
<label for="show3">Show</label>
</li>
<li>
<input type=radio id="show4" name="group">
<label for="show4">Show</label>
</li>
<li>
<input type=radio id="show5" name="group">
<label for="show5">Show</label>
</li>
</ul>
<div id="content">Content</div>
最佳答案
#content {
display: none;
}
.show:checked ~ #content {
display: block;
}
<input type="radio" name="show" id="show1" class="show">
<label for="show1">Show</label>
<input type="radio" name="show" id="show2" class="hide">
<label for="show2">Hide</label>
<div id="content">Contents here</div>
~
选择器只针对同级元素。由于您的 :checked
输入是嵌套的,因此它实际上不是 #content
div 的兄弟。 ul
和 div
是兄弟。 input
和它的 label
是兄弟。并且一个 li
是下一个 li
的兄弟。但是要从 input
到 div#content
,您必须在 dom 中上升几层。因此,不是 sibling 。
您必须更改标记的设置方式(示例见下面的代码片段;我添加“隐藏”框只是为了更容易看到效果,但重要的是输入和 div 是 sibling ),或者更改您处理隐藏/显示行为的方式。
关于html - 为什么 :checked class not working in nested ul li. 尝试使用检查类显示内容 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44830491/