我有一个小的jQuery函数,其中返回值必须在子函数中触发。原因:我想稍后将此功能与其他jQuery函数链接在一起。但是下一个链接函数应该在主函数返回jQuery对象之后开始
app.h.aniend = 'webkitAnimationEnd oanimationend msAnimationEnd animationend';
$.fn.animate_scale = function( callback ) {
var $this = $(this);
$this.addClass('animate_scale').one( app.h.aniend, function() {
$(this).removeClass('animate_scale');
if( typeof callback === 'function' ) {
callback($this);
}
return $this; // return here...
});
// return $this;
};
有没有说jQuery要等到子功能返回必要的jQuery对象进行链接?
$('#my_object').animate_scale().fadeOut(2000);
最佳答案
如果您希望.fadeOut()
等待animate_scale()
完成,则需要将animate_scale
排队:
排队您的插件:
通常,当您像这样链 fx methods时,即:
$("#ball").animate({left:200}).fadeOut();
您将看到球动画,并且只有在动画结束后---它才会淡出。为什么? 原因jQuery会将
animate
和比fadeOut
散布到queue
数组中,并等待它们解析后再触发下一个Method。要在插件中复制相同的行为,请执行以下操作:
jsFiddle demo (Queue in action!)
$.fn.animate_scale = function( callback ) {
var $this = this;
return $this.queue(function() {
$this.addClass('animate_scale').on("animationend", function() {
$this.dequeue();
if (typeof callback == 'function') callback.call( $this );
});
});
};
$('#my_object').animate_scale(function() {
console.log( "Scale is done!" );
}).fadeOut( 2000 ); // fadeOut will wait for animate_scale to dequeue (complete)
我不需要队列堆叠
如果您希望插件顺利地(同时)处理其他链式fx方法,
仅使用回调:
jsFiddle demo (no Queue)
$.fn.animate_scale = function( callback ) {
var $this = $(this);
return $this.addClass('animate_scale').on("animationend", function() {
if (typeof callback == 'function') callback.call( this );
});
};
$('#my_object').animate_scale(function(){
console.log("Scale done.");
// use $(this).fadeOut(2000); here!! cause otherwise...
}).fadeOut(2000); // ...if chained here, will fade immediately!!!!!