将鼠标悬停在其他标记元素上

时间:2014-02-08 15:59:30

标签: javascript html css

当鼠标悬停在元素上时,我尝试将鼠标悬停在其他标记元素上。但是它不起作用,当两个元素都在同一个div标签中时它会起作用。

HTML

<div id="wrap">
<div id="wrap1">
    <div class="a" id='aa'>AAAA</div>
</div>
<div id="wrap2">
    <div class ="b" id='bb'>BBBB</div>
</div>
</div>

CSS

.a {
    color: red;
}

.b {
    color: orange;
}

#aa:hover ~ #bb {
    background-color: blue;
}

* 注意: *我不想使用jQuery

2 个答案:

答案 0 :(得分:2)

这不能在纯CSS中完成,你必须编写一些JS。

我建议使用jQuery,因为它使这些操作非常容易,例如在你的情况下:

$('#aa').hover(
    function() {
        $('#bb').css('background-color','blue')
    },
    function() {
        $('#bb').css('background-color','')
    }
)

演示:http://jsfiddle.net/9nN6W/

通过一点点努力,同样可以在普通的香草JS中完成,但为什么要发明轮子。

如果你想在纯CSS中这样做,元素必须可以通过CSS访问,例如你可以定位“换行”DIV:

#wrap1:hover ~ #wrap2 {
    background-color: blue;
}

演示:http://jsfiddle.net/9nN6W/1

受欢迎的要求:纯JS解决方案

document.getElementById('aa').addEventListener('mouseenter', 
    function() {
        document.getElementById('bb').style.backgroundColor = 'blue';
    }
)

document.getElementById('aa').addEventListener('mouseleave', 
    function() {
        document.getElementById('bb').style.backgroundColor = '';
    }
)

演示3:http://jsfiddle.net/9nN6W/2/

答案 1 :(得分:0)

Javascript就是: - )

document.getElementById("aa").onmouseover=function(){
        document.getElementById("bb").style.backgroundColor="blue";     
    };
    document.getElementById("aa").onmouseout=function(){
        document.getElementById("bb").style.backgroundColor="";
    };