简体   繁体   中英

CSS3 - hover from one div into another

I can't figure out how to or is it even possible, to change one div's child's attributes when hovering over other div's child.

Here is the example. http://jsfiddle.net/0m0468f6/3/

<div id='bigdiv1'>
<div id='smalldiv1'></div>
</div>
<div id='bigdiv2'>
<div id='smalldiv2'></div>
</div>

#smalldiv1:hover~#smalldiv2{
background:yellow;}

More precisely, how to change one div's attributes hovering over another, while the two of those are located separately in two wrappers. Is it possible with only css3, and if not - is there any other way to style the html.

See this fiddle

I've used onmouseover and onmouseout events.

HTML

<div id='bigdiv1'>
    <div id='smalldiv1' onmouseover="chbg('yellow')" onmouseout="chbg('green')">
    </div>
</div>
<div id='bigdiv2'>
    <div id='smalldiv2'>
    </div>
</div>

JS

function chbg(color) {
    document.getElementById('smalldiv2').style.backgroundColor = color;
}

In css it is only possible to change the attribute of child elements or itself.

#bigdiv2:hover #smalldiv2{
    background:yellow;
}

http://jsfiddle.net/0m0468f6/7/

In this html structure i would do it with JavaScript.

var smalldiv1 = document.getElementById('smalldiv1');
var smalldiv2 = document.getElementById('smalldiv2');

smalldiv1.onmouseover = function(event){
    smalldiv2.style.backgroundColor = 'yellow';
};

smalldiv1.onmouseout = function(event){
    smalldiv2.style.backgroundColor = 'green';
};

http://jsfiddle.net/0m0468f6/8/

Assuming you can use a #wrapper element and you need to support only modern browser, a pure css solution could involve pointer-events and clip-path properties

http://jsfiddle.net/kmao8uk2/4/

The CSS inserted is

#wrapper { position: relative; }

#smalldiv1 {
    position: absolute;
    z-index: 2;
    pointer-events: none;
}

#smalldiv2 {
    padding-top: 0px;
    position: absolute;
    top: 0;
    padding-top: 200px;
    z-index: 1;

    -webkit-clip-path: polygon(100% 0, 100% 33%, 0 33%, 
         0 66%, 100% 66%, 100% 100%, 100% 100%, 0 100%, 0 0);
    clip-path: polygon(100% 0, 100% 33%, 0 33%, 0 66%, 
         100% 66%, 100% 100%, 100% 100%, 0 100%, 0 0);    

}


#smalldiv2:hover {
    background-color:yellow;
}

I changed the size of your #smalldiv2 so now it is 300px tall, but thanks to clip-path its shape is empty in the red part.

As a result #smalldiv1 covers #smalldiv2 but when you hover the first one, the cursor-pointer property so defined will pass the hover event to the elements underlying, so it's like you're actually hovering #smalldiv2 .

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