【问题标题】:jquery add delay on hover-out animation only if previous animation is completejQuery仅在前一个动画完成时才在悬停动画上添加延迟
【发布时间】:2012-03-16 14:58:22
【问题描述】:

我有一个小的jQuery sn-p,它根据图像的alt 属性(如果存在)为图像标题设置动画。

它工作正常,但我有一个小问题。我想要一个悬停 (slideUp) 动画上的 delay,但如果之前的 slideIn 动画完全完成。在基本场景中:

场景 1: 用户将鼠标悬停在图像上,字幕完全动画化。用户悬停在外,动画延迟(字幕保持不变)2 秒,然后动画化。

场景 2:用户将鼠标悬停在图像上,标题开始动画化,但用户在完成之前悬停在外。动画应立即停止并延迟。

场景 1 完美运行。场景2没有。延迟发生在部分动画元素滑出之前,这是不希望的。我可以看到我的代码中的缺陷,但似乎无法弄清楚如何解决它。

Fiddle,以及当前脚本:

$('.pv-inner').hover(function() {

    var img = $(this).find('img:first');
    var text = img.attr('alt');

    if (text !== undefined) {
        //remove any existing captions
        $(this).find('.kppImageCaption').remove();

        //insert the new caption
        img.after('<div class="kppImageText">' + text + '</div><div class="kppImageCaption"></div>');

        //animate it in
        $(this).find('.kppImageCaption').stop().slideDown('slow').animate({
            opacity: 0.6
        }, {
            queue: false,
            duration: 'slow',
            complete: function() {
                $(this).parent().find('.kppImageText').fadeTo(1000, 1);
            }
        });
    }
}, function() {

    //on hover out animate it out. Here is the problem. I only want the delay 
    //to occur if the above hover over animation completed - currently it delays
    //in all cases.
    $(this).find('.kppImageCaption, .kppImageText').stop().delay(2000).slideUp('slow', function() {
        $(this).remove();
    });

});

编辑

Final working fiddle。可以帮助未来的人。

【问题讨论】:

    标签: jquery css delay jquery-animate


    【解决方案1】:

    创建变量,我们称之为var animationStatus = false 在开始动画之前,设置animationStatus = true

    complete 函数中(参见jQuery animate docs)设置animationStatus = false

    在您负责隐藏的函数中 - 创建 if 语句。如果 animationStatus === false - 延迟。如果 animationStatus === true - 没有延迟。

    祝你好运!

    【讨论】:

    • 谢谢,我会试试这个 - 如果我在使用这个脚本的页面上有多个图像,我假设他们会共享那个变量?我对 js 中的范围很残酷。还在考虑使用/检测 css 类作为标志..
    • 感谢您的帮助。我使用了您建议的相同方法,但使用 css 类标志以确保如果我在页面上有多个带有标题的图像,则 js 范围不会成为问题。最后的小提琴:jsfiddle.net/r4bzE/11
    • 很高兴听到这个消息:) 这也是我试图解释一个想法而不是提供一个可行的解决方案(代码)的原因。喜欢看看人们是如何自己做的:)
    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多