简体   繁体   中英

Hover over/click on div to affect another div?

I'm trying to affect 3 other div's when I hover over/click on one but it doesn't want to work.

#header2:hover {
background-color: rgba(10,50,10,0.9);
}
#header2:active {
    background-color: rgba(0,0,0,0);
}
#header2:active ~ #header1{
    background-color: rgba(0,0,0,0.8);
}
#header2:active ~ #header3{
    background-color: rgba(50,10,10,0.8);
}
#header2:active ~ #header4{
    background-color: rgba(10,10,50,0.8);
}

https://jsfiddle.net/ThinkingStiff/a3y52/ In this example I found whilist trying to find out the problem, it works fine, and I can't see any differences. The elements aren't children or parents of eachother either. (And I'd like to fix this without Javascript/Jquery if possible)

My HTML:

<div id="header1"><a data-scroll id="link1" href="#header1content"></a></div>
<div id="header2"><a data-scroll id="link2" href="#header2content"></a></div>
<div id="header3"><a data-scroll id="link3" href="#header3content"></a></div>
<div id="header4"><a data-scroll id="link4" href="#header4content"></a></div>

In order to make this work, #header2 should be the first element in your markup. Because ~ selector in css can select elements which are preceded (Not followed) by a specific element.

Therefore If you wants to style different elements on hover of #header2 then #header2 should come first in markup. In the same way if you wants to style different elements on hover of #header4 then #header4 should come first in markup.

With css flex you can change order of elements. It has an order property for child elements that can change order. You can make it work as shown below:

 .headers { flex-direction: column; display: flex; } .headers div { background: #ccc; margin: 0 0 10px; height: 50px; } #header2 {order: 2;} #header1 {order: 1;} #header3 {order: 3;} #header4 {order: 4;} #header2:hover { background-color: rgba(10,50,10,0.9); } #header2:active { background-color: rgba(0,0,0,0); } #header2:active ~ #header1, #header2:hover ~ #header1 { background-color: rgba(0,0,0,0.8); } #header2:active ~ #header3, #header2:hover ~ #header3 { background-color: rgba(50,10,10,0.8); } #header2:active ~ #header4, #header2:hover ~ #header4 { background-color: rgba(10,10,50,0.8); } 
 <div class="headers"> <div id="header2"><a data-scroll id="link2" href="#header2content">Header 2</a></div> <div id="header1"><a data-scroll id="link1" href="#header1content">Header 1</a></div> <div id="header3"><a data-scroll id="link3" href="#header3content">Header 3</a></div> <div id="header4"><a data-scroll id="link4" href="#header4content">Header 4</a></div> </div> 

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