首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jQuery .animate()的自定义回调

jQuery .animate()的自定义回调
EN

Stack Overflow用户
提问于 2013-08-21 17:26:48
回答 2查看 129关注 0票数 1

我正在尝试为jQuery .animate()函数创建一个自定义回调。我仅限于使用jQuery 1.4.2,并根据的这篇文章进行定制调用。

代码语言:javascript
运行
复制
(function ($){
    var oldAnimate = $.fn.animate;
    $.fn.animate = function(){
        this.trigger('animate.before', arguments);
        var animateResult = oldAnimate.apply(this, arguments);
        this.trigger('animate.after', arguments);
        return animateResult;
    };
})(jQuery || {});

$('#ID').bind('animate.after', function (){ 
    //Do Something
});

但是,当我运行这段代码时,我的‘//做某事’不会触发。我还试着跟踪Dave的文章,并使用以下方法:

代码语言:javascript
运行
复制
var oldAnimate = jQuery.animate;

jQuery.animate = function() {
    if (typeof animate.before === 'function')
    animate.before.apply(this, arguments);
    var animateResult = oldAnimate.apply(this, arguments);
    if (typeof animate.after === 'function')
    animate.after.apply(this, arguments);
    return animateResult;
};

我不知道我哪里出了问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-21 17:50:29

好的,你已经发现你的代码不工作了。第一步是简化它,并分别测试它的各个部分。让我们从事件开始。

代码语言:javascript
运行
复制
$("#ID").bind("animate.before animate.after",function(e){
   console.log(e.type); 
}).trigger("animate.before").trigger("animate.after");

这将导致两次以相等于“动画”的类型触发的两个事件。若要使其在前面和之后显示为动画,请将.替换为:

代码语言:javascript
运行
复制
$("#ID").bind("animate:before animate:after",function(e){
   console.log(e.type); 
}).trigger("animate:before").trigger("animate:after");

现在我们正确地得到了animate:beforeanimate:after。现在我们已经知道我们的事件是有效的,让我们将其绑定到动画方法中。

代码语言:javascript
运行
复制
$("#ID").bind("animate:before animate:after",function(e){
   console.log(e.type); 
});

var oldanim = $.fn.animate;
$.fn.animate = function() {
    this.trigger("animate:before");
    oldanim.apply(this,arguments);
    this.trigger("animate:after");
};

$("#ID").animate({"width":"200px"},2000,function(){
    console.log("animation complete");
});

很管用!但是,您会很快地注意到,事后事件发生的时间比应该的要晚。这是因为动画方法使用setTimeouts以异步方式执行,因此代码继续运行。到目前为止,我还没有任何建议来解决这个问题,因为我们没有延迟到1.5的对象。您可以重写整个函数,但是您必须考虑到它可以以两种不同的方式附加。

票数 1
EN

Stack Overflow用户

发布于 2013-08-21 17:36:35

complete选项怎么样?我想这可以在jQuery 1.4.1中找到。

代码语言:javascript
运行
复制
$('#id').animate({
    properties..
}, {
    complete: function() {
        // doStuff
    }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18363958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档