我在css上编码有一个很大的问题
HTML
<div id='wrapper'>
<div id='first'></div>
...
</div>
...
<div id='second'></div>
CSS
<style>
#first:hover ~ #second
{
background:#000;
}
</style>
但它不起作用。当div[id=second]
悬停时,我需要更改div[id=first]
的背景。
答案 0 :(得分:2)
Tilde ~
是兄弟选择器,但#second
不是HTML中#first
的兄弟。您需要将#second
放在包装内,以使~
生效。
<style>
#first:hover ~ #second
{
background:#000;
}
</style>
<div id='wrapper'>
<!-- Now they share the same parent, so they are siblings -->
<div id='first'>Hover over first</div>
<div id='second'>To black out second</div>
</div>
如果#second
需要在#wrapper
之外,则必须使用Javascript在鼠标移过#second
时更改#first
的样式。普通的CSS不允许您选择“堂兄弟”。
<script>
var third = document.getElementById('third'),
fourth = document.getElementById('fourth');
third.addEventListener('mouseover', function () {
fourth.className = "blackout"
});
third.addEventListener('mouseout', function () {
fourth.className = "";
});
</script>
<style>
.blackout {
background:#000;
}
</style>
<div id='wrapper2'>
<div id='third'>Hover over third</div>
</div>
<div id='fourth'>To black out fourth</div>