简体   繁体   中英

When hover a link change other div background

I have two div s, one with a list of links (projects) and another empty. My goal is to whenever I hover a link on the first div , the background of the second div changes to the project corresponding image. Here is an example of what I'm trying to accomplish https://www.humbertpoyet.com/about/press and here is my code. Thank you

HTML

<div class="wrapper">
    <div class="grid-container">
        <div class="item6">
            <ul>
                <li><h3>Case Studys</h3></li>
                <li><a href="#">Project 1</a></li>
                <li><a href="#">Project 2</a></li>
                <li><a href="#">Project 3</a></li>
                <li><a href="#">Project 4</a></li>
            </ul>
        </div>
        <div class="item6 thumb">
    </div>
</div>

CSS

.item6 {grid-column: span 6;}
.thumb {background-size: cover; background-position: center; background-repeat: no-repeat;}

You can use the following jQuery function. Note that you have to set a height for .thumb , otherwise it will be invisble due to no content, which results in height 0.

 $('.item6>ul>li:nth-child(2)').hover(function() { $('.item6.thumb').css('background-image', 'url(https://placehold.it/600x400/fa0)'); }); $('.item6>ul>li:nth-child(3)').hover(function() { $('.item6.thumb').css('background-image', 'url(https://placehold.it/800x300/09b)'); }); $('.item6>ul>li:nth-child(4)').hover(function() { $('.item6.thumb').css('background-image', 'url(https://placehold.it/300x500/d2c)'); }); $('.item6>ul>li:nth-child(5)').hover(function() { $('.item6.thumb').css('background-image', 'url(https://placehold.it/100x300/aa4)'); });
 .item6 { grid-column: span 6; } .thumb { height: 300px; background-size: cover; background-position: center; background-repeat: no-repeat; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> <div class="grid-container"> <div class="item6"> <ul> <li> <h3>Case Studys</h3> </li> <li><a href="#">Project 1</a></li> <li><a href="#">Project 2</a></li> <li><a href="#">Project 3</a></li> <li><a href="#">Project 4</a></li> </ul> </div> <div class="item6 thumb"> </div> </div>

If you add data-url to your list items, you can use JQuery to capture when the user hovers above the list item, take the desired image and replace the background of the second div.

<li data-url='url("paper.gif")'><h3>Case Studys</h3></li>


$(".item6").on("mouseenter", "li", function(){
    let imageUrl = $(this).attr("data-url");
    $(".item6.tumb").css("background-image", imageUrl);
});

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