jQuery fade flickers

断了今生、忘了曾经 提交于 2019-11-28 04:58:43

问题


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

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.

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.

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');

    });

});

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="http://dougie.thewestharbour.com/wp-content/uploads/store-front.jpg" alt="store front" title="store-front" width="730" height="360" class="alignnone size-full wp-image-98" /></li>

Thanks,

Wade


回答1:


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);
})

Example →




回答2:


As the other answer mentions, fadeOut sets display:none at the end, so the element no longer affects the layout of the page. The suggestion to just animate the opacity is correct, but there is already a function for doing so, fadeTo, which is a wee bit cleaner than writing the animation yourself:

$('.main-overlay').hover(
    //Mouseover, fadeIn the hidden hover class 
    function() {
        $(this).fadeTo(0,1000);
    },
   //Mouseout, fadeOut the hover class
    function() {
        $(this).fadeTo(1,1000);   
})


来源:https://stackoverflow.com/questions/5967313/jquery-fade-flickers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!