html - 为什么 :checked class not working in nested ul li. 尝试使用检查类显示内容 div

标签 html css

我尝试使用 :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 的兄弟。 uldiv 是兄弟。 input 和它的 label 是兄弟。并且一个 li 是下一个 li 的兄弟。但是要从 inputdiv#content,您必须在 dom 中上升几层。因此,不是 sibling 。

您必须更改标记的设置方式(示例见下面的代码片段;我添加“隐藏”框只是为了更容易看到效果,但重要的是输入和 div 是 sibling ),或者更改您处理隐藏/显示行为的方式。

关于html - 为什么 :checked class not working in nested ul li. 尝试使用检查类显示内容 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44830491/

相关文章:

CSS反向过渡并选择 previous sibling

javascript - 我可以使用 Ajax 更改文本框的值吗

html - 更改 CSS 位置而不是在屏幕上移动对象

html - SVG中的反透明区域

javascript - 在 CSS 和 HTML 中创建灯 zipper

html - 谷歌应用程序脚本中的彩色按钮

javascript - 使用 jQuery 改变 div 的颜色

css - 一旦 IE8 问题,单击按钮后禁用按钮

javascript - 单击按钮后更改模式的内容

html - 双面盒阴影