在只有css的情况下,如何显示/隐藏一个知道其id的div?
对于jQuery来说,使用普通的javascript会很简单,甚至更简单,但是如何使用css来实现呢?
checkbox黑客需要有一个特定的结构才能工作
另外,我希望它只在下一个h1之前隐藏div,如果有的话。
label:after {
content: " [show]";
cursor: pointer;
float: right;
}
p {
display: none;
}
input[type=checkbox] {
display: none;
}
input[type=checkbox]:checked + div {
display: block;
}
input[type=checkbox]:checked ~ label:after {
content: " [hide]"
}
<h1>
Vampires and Vegetarians
<label for="Vampires_and_Vegetarians"></label>
</h1>
<input type="checkbox" id="Vampires_and_Vegetarians">
<div id="Vampires_and_Vegetarians">
<p>Content for Vampires and Vegetarians</p>
</div>
发布于 2018-06-21 21:37:15
为了让你的checkbox控制一些东西,它必须在dom
中出现在它的前面,所以我把它移到了最上面。
我还稍微改变了你的CSS,你隐藏了p
,然后试图显示div
,现在我们隐藏了div
,然后显示它。
我还将+
更改为~
,因为div
不是直系兄弟。
input[type=checkbox] {
display: none;
}
input[type=checkbox]:checked~h1 label:after {
content: " [hide]"
}
label:after {
content: " [show]";
cursor: pointer;
float: right;
}
input[type=checkbox]~div {
display: none;
}
input[type=checkbox]:checked~div {
display: block;
}
<section>
<input type="checkbox" id="Vampires_and_Vegetarians">
<h1>
Vampires and Vegetarians
<label for="Vampires_and_Vegetarians"></label>
</h1>
<div id="Vampires_and_Vegetarians">
<p>Content for Vampires and Vegetarians</p>
</div>
</section>
<section>
<input type="checkbox" id="Zombies_and_Zucchini">
<h1>
Zombies and Zucchini
<label for="Zombies_and_Zucchini"></label>
</h1>
<div id="Zombies_and_Zucchini">
<p>Content for Zombies and Zucchini</p>
</div>
</section>
我希望这对你有帮助
请随时要求澄清。
发布于 2018-06-21 21:35:34
您需要更改元素的层次结构,如下所示。因为~
用于定位下一个同级元素,而不是前一个元素。另外,不要两次使用相同的id
label:after {
content: " [show]";
cursor: pointer;
float: right;
}
.content {
display: none;
}
input[type=checkbox] {
display: none;
}
input[type=checkbox]:checked~.content {
display: block;
}
input[type=checkbox]:checked~h1 label:after {
content: " [hide]"
}
<div>
<input type="checkbox" id="1">
<h1>
1
<label for="1"></label>
</h1>
<div class="content">
<p>Content for 1</p>
</div>
</div>
<div>
<input type="checkbox" id="2">
<h1>
2
<label for="2"></label>
</h1>
<div class="content">
<p>Content for 2</p>
</div>
</div>
https://stackoverflow.com/questions/50969637
复制相似问题