简体   繁体   中英

jQuery :hover Div to reveal Sibling

I have the following in jQuery

// Larger sidebar images fades in on :hover
$("#left_sidebar .img_contain").hover(function(){
    $(this).find(".larger_img").fadeIn("slow");
    $(this).find(".larger_img").fadeOut("slow");
});

With the following HTML

        <div class="img_contain">
        <img width="160" height="240" src="/smaller.jpg">
        <div class="larger_img" style="display: none; ">
              <img width="300" height="450" src="/larger.jpg">
            </div>
    </div>

The idea here is that on:hover the hidden .larger_img div should fade in. The code works as expected but has a quirk - when hovering the .larger_img div successfully fades in but immediately fades out. My intention here is that the .larger_img div remains visible as long as the .img_contain div is:hovered.

Help?

I think this is your intention:

$("#left_sidebar .img_contain").hover(function(){
    $(this).find(".larger_img").fadeToggle("slow");
});

You are both fading in and fading out the same element upon each mouseover and mouseout. You need to either:

1 - Separate both fade operations into two functions:

$("#left_sidebar .img_contain").hover(function(){
    $(this).find(".larger_img").fadeIn("slow");
}, function() {
    $(this).find(".larger_img").fadeOut("slow");
});

2 - Use a toggling method or technique within the 'single function' version of the .hover event handler. (as in the first snippet).

Here you go

Working demo

hover takes 2 functions which was the issue in your code. If you pass only one function it will call it onmouseover as well as mouseout event.

Change your JavaScript to this:

$("#left_sidebar .img_contain").hover(
    function() {$(this).find(".larger_img").fadeIn("slow");},
    function() {$(this).find(".larger_img").fadeOut("slow");}
);

You are not doing the hover properly.

Demo

However the following code is much more smooth and optimized:

$("#left_sidebar .img_contain").hover(
    function() {$(".larger_img",this).stop(true, true).fadeIn("slow");},
    function() {$(".larger_img",this).stop(true, true).fadeOut("slow");}
);

Optimized Demo

$(".img_contain").hover(function(){
    $(this).find(".larger_img").fadeIn("slow");
},function(){
    $(this).find(".larger_img").fadeOut("slow");    
})

generally .hover takes two functions. It can take one, which serves as both the hover on and hover off function. That is why you see it both fade in and out twice.

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