Css选择器 - 不同级别

时间:2014-07-31 19:04:48

标签: html css css-selectors

我在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]的背景。

1 个答案:

答案 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>

Check out the live demo in a jsFiddle