【问题标题】:jQuery fade flickersjQuery淡化闪烁
【发布时间】:2011-05-11 16:06:21
【问题描述】:

我这里有 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>

谢谢,

韦德

【问题讨论】:

    标签: jquery hover fadein fade fadeout


    【解决方案1】:

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

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

    Example →

    【讨论】:

    • 我非常喜欢这个解决方案!但是元素不会保持可见,可能会覆盖背景中不应该覆盖的东西吗?
    【解决方案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);   
    })
    

    【讨论】:

    • 虽然这个解决方案有效(并且肯定比使用animate 更干净),但fadeTo 方法实际上是.fadeTo( duration, opacity [, complete ] )。所以上面应该是 FadeIn:fadeTo(1000, 0) 和 FadeOut:fadeTo(1000, 1)。很好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 2014-10-02
    • 2012-04-23
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多