jQuery淡化闪烁jQuery

2023-09-07 22:12:39 作者:上善若水﹏

我在这里有 jQuery 淡入淡出:http://dougie.thewestharbour.com/

I have jQuery fade going here: http://dougie.thewestharbour.com/

当您将鼠标悬停在 .main-overlay div 上时,我希望它淡出,然后当您将鼠标移开时,我希望它淡入.

When you hover over the .main-overlay div I would like it to fade out then when you take your mouse off of it, I would like it to fade back in.

但是,您现在可以看到它只是在闪烁.我猜这是因为 div 消失了,所以当它淡出时它被视为 mouseout 但我不知道如何解决它.

However, you can see it's just flickering right now. I'm guessing it's because the div disappears so it's treated as a mouseout when it's faded out but I'm not sure how to go about solving it.

这是我的 javascript:

Here is my javascript:

    $(document).ready(function () {


    $('.main-overlay').hover(

        //Mouseover, fadeIn the hidden hover class 
        function() {

            $(this).fadeOut('1000');

        },

        //Mouseout, fadeOut the hover class
        function() {

            $(this).fadeIn('1000');   

    }).click (function () {

        //Add selected class if user clicked on it
        $(this).addClass('selected');

    });

});

这是覆盖 div 附加到的项目之一:

And here is one of the items that the overlay div is attached to:

<li><div class="main-overlay"></div><span class="caption">The store front</span><img src="https://m.xsw88.com/allimgs/daicuo/20230907/6539.png.jpg" alt="store front" title="store-front" width="730" height="360" class="alignnone size-full wp-image-98" /></li>

谢谢,

韦德

推荐答案

之所以会这样,是因为 fadeOut 末尾有一个 display:none,所以当你移动时fadeOut 完成后,您的鼠标将触发取消悬停功能.相反,只需 animate opacity:

It's happening because fadeOut has a display:none at the end of it, so when you move your mouse after the fadeOut has completed it will trigger the unhover function. Instead, just animate the opacity:

$('.main-overlay').hover(function() {
    $(this).animate({opacity: 0}, 1000);
}, function() {
    $(this).animate({opacity: 1}, 1000);
})

示例 →