我正在尝试为jQuery .animate()函数创建一个自定义回调。我仅限于使用jQuery 1.4.2,并根据的这篇文章进行定制调用。
(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的文章,并使用以下方法:
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;
};
我不知道我哪里出了问题。
发布于 2013-08-21 17:50:29
好的,你已经发现你的代码不工作了。第一步是简化它,并分别测试它的各个部分。让我们从事件开始。
$("#ID").bind("animate.before animate.after",function(e){
console.log(e.type);
}).trigger("animate.before").trigger("animate.after");
这将导致两次以相等于“动画”的类型触发的两个事件。若要使其在前面和之后显示为动画,请将.
替换为:
。
$("#ID").bind("animate:before animate:after",function(e){
console.log(e.type);
}).trigger("animate:before").trigger("animate:after");
现在我们正确地得到了animate:before
和animate:after
。现在我们已经知道我们的事件是有效的,让我们将其绑定到动画方法中。
$("#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的对象。您可以重写整个函数,但是您必须考虑到它可以以两种不同的方式附加。
发布于 2013-08-21 17:36:35
complete
选项怎么样?我想这可以在jQuery 1.4.1中找到。
$('#id').animate({
properties..
}, {
complete: function() {
// doStuff
}
});
https://stackoverflow.com/questions/18363958
复制相似问题