jQuery淡入淡出闪烁问题

5
我这里有一个jQuery淡入淡出效果:http://dougie.thewestharbour.com/ 当你将鼠标悬停在 .main-overlay div 上时,我希望它淡出,然后当你将鼠标移开时,我希望它淡入。
但是,你可以看到它现在只是闪烁。我猜测这是因为div消失了,所以当它淡出时被视为mouseout,但我不知道如何解决它。
这是我的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所附加的项目:

<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>

感谢您的来信,
Wade
2个回答

11

这是因为fadeOut在末尾有一个display:none,所以当你在fadeOut完成后移动鼠标时,它将触发取消悬停功能。 相反,只需将opacity进行animate

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

示例 →


1
我非常喜欢那个解决方案!但是该元素不会一直可见吗?可能会遮挡它不应遮挡的背景物品吧? - SquareCat

2
正如其他答案所提到的,fadeOut在最后设置display:none,因此该元素不再影响页面的布局。建议仅动画化透明度是正确的,但已经有一个函数可以做到这一点,fadeTo,它比自己编写动画代码更加简洁:
$('.main-overlay').hover(
    //Mouseover, fadeIn the hidden hover class 
    function() {
        $(this).fadeTo(0,1000);
    },
   //Mouseout, fadeOut the hover class
    function() {
        $(this).fadeTo(1,1000);   
})

3
尽管这个解决方案可行(而且肯定比使用animate更干净),但fadeTo方法实际上是.fadeTo(duration,opacity[,complete])。因此,以上应该为FadeIn:fadeTo(1000,0)和FadeOut:fadeTo(1000,1)。所有这些都是好的解决方案。 - Josh Frankel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接