简体   繁体   中英

CSS hover div change another div style (not under same parent)

See Example 3 in fiddle below...

https://jsfiddle.net/8opnvq37/1/

HTML

Example 1
<div class="a">A</div>
<div class="b">B</div>
<br /><br />
Example 2
<div class="a">A</div>
<div id="box"><div class="b">B</div></div>
<br /><br />
Example 3
<div id="box2"><div class="a">A</div></div>
<div class="b">B</div>

CSS

.a:hover ~ .b,
.a:hover ~ #box .b
{
background: #3F6;
}

As you can see Example 1 & 2 are working when you hover over A. I know for the hover effect to work, the elements has to be under the same parent— unless you specify it— in Example 2. But how do you get it to work when .a is under a different parent as shown in Example 3??

Does it absolutely need to be hovering on the .a element? I'm not sure it's possible with pure css if so. This would work, though:

#box2:hover ~ .b { background: #3f6; }

Ok I got that to work using javascript

http://jsfiddle.net/6vh5L2t0/

HTML

<div id="c">Div C</div>
---
<div id="box">
<div id="d">Div D</div></div>

Javascipt

$('#d').hover(
function(){
$('#c').css('background', '#F00')
}, 
function() { 
$('#c').css('background', '')
});

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