简体   繁体   中英

hover on other tag element

I try to do hover on other tag element when mouse over on a element. but its not working, it is working when both elements are in same div tag.

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;
}

* Note: *I don't want to use jQuery .

This cannot be done in pure CSS, you will have to write some JS.

I suggest using jQuery since it makes these kinds of manipulations very easy eg in your case:

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

Demo: http://jsfiddle.net/9nN6W/

With a little more effort same can be done in plain vanilla JS as well, but why invent the wheel.

If you want to do this in pure CSS, elements have to be accessable via CSS, for example you can target the "wrap" DIVs:

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

Demo : http://jsfiddle.net/9nN6W/1

By popular requests: Pure JS solution

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

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

Demo 3: http://jsfiddle.net/9nN6W/2/

Javascript it is then :-)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM