我一直在测试CSS选择器。当我将p
悬停时,我想更改h3
的显示,所以我写了类似的内容:
div > p{
display: none;
}
div > h3:hover p{
display: block;
}
<div>
<h3>Lorem ipsum dolor sit amet</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
但它不起作用。这有什么不对?我错过了什么?
答案 0 :(得分:8)
div > p {
display: none;
}
div > h3:hover + p {
display: block;
}
<div>
<h3>HOVER ME</h3>
<p>Lorem ipsum dolor sit amet...</p>
</div>
回顾
h3 p
...表示p
是h3
的后代
h3 + p
...意味着p
是h3
如果您计划在不久的将来在h3
和p
之间使用其他元素而不是General sibling selector ~
,那么
div > p {
display: none;
}
div > h3:hover ~ p { /* notice the general sibling selector */
display: block;
}
.line{background: red; height: 1px; }
<div>
<h3>HOVER ME</h3>
<div class="line"></div>
<p>Lorem ipsum dolor sit amet...</p>
</div>
答案 1 :(得分:3)
您可以使用相邻的兄弟选择器(+
),例如div > h3:hover + p
。
见下面的演示:
div>p {
display: none;
}
div>h3:hover+p {
display: block;
}
<div>
<h3>Lorem ipsum dolor sit amet</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>