简体   繁体   中英

Change CSS of a div when hovering another (JQuery)

I want to change the CSS of a div when hovering its parent div.

This is my HTML:

<div id="box1" class="hover-on-div-1">
    <img src="images/1.png" alt="" />
    <div id="line1"></div>
    <div class="text_align"><span>Text here</span>
    </div>
</div>

Here is the CSS:

#box1 {
    height: 295px;
    width: 220px;
    background-color: #86d1f4;
    float: left;
    margin-left: 30px;
    margin-right: 120px;
    margin-top: 55px;
    color: #0081C5;
}

#box1:hover {
    background-color: #494c5b;
    color: #BFB6AF;
}

#line1 {
    height:1px;
    background:#0081C5;
    width:126px;
    margin-top:67px;
    margin-left:40px;
    position:absolute;
}

Note: .hover-on-div-1 is the class I use for a JQuery function that changes the image, the <span> is used only for a text-transform and the text-align class is pretty self explanatory.

How do I change the .line1 div when hovering over #box1?

I managed to change everything inside the #box1 div when I hover but not the .line1. Did some search on SO but since I'm a total noob when it comes to JQuery/JavaScript it didn't helped too much.

https://jsfiddle.net/nLg8Lr7x/

You don't need JS for this - your #line1 div is child of #box1 div . Just add some css like this:

#box1:hover #line1 {
    /* Changes for #line1 when #box1 hovered */
}

Here is examle on jsbin .

If you want to do it with jQuery you can make use of mouseover and mouseleave functions to change css like below.

Notes: I suggest you to make use of addClass and removeClass functions instead of setting hard codded css in functions.

$('#box1').mouseover(function() {
   $('#line1').css("background", "red"); // change css
});
$('#box1').mouseleave(function() {
   $('#line1').css("background", "#0081C5"); // change back css as it was
});

 $('#box1').mouseover(function() { $('#line1').css("background", "red"); }); $('#box1').mouseleave(function() { $('#line1').css("background", "#0081C5"); }); 
  #box1 { height: 295px; width: 220px; background-color: #86d1f4; float: left; margin-left: 30px; margin-right: 120px; margin-top: 55px; color: #0081C5; } #box1:hover { background-color: #494c5b; color: #BFB6AF; } #line1 { height: 1px; background: #0081C5; width: 126px; margin-top: 67px; margin-left: 40px; position: absolute; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="box1" class="hover-on-div-1"> <img src="images/1.png" alt="" /> <div id="line1"></div> <div class="text_align"><span>Text here</span> </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