我有一个小的 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);
最佳答案
$('#my_object').animate_scale().fadeOut(2000);
如果您希望.fadeOut()
等待animate_scale()
完成,animate_scale
需要排队:
对您的插件进行排队:
通常,当您链式 fx methods就像:
$("#ball").animate({left:200}).fadeOut();
你会看到球有动画,只有当动画完成后——它才会淡出。
为什么? 因为 jQuery 会将 animate
和 fadeOut
放入 queue
数组中,并在触发之前等待它们解析下一个方法。
要在插件中复制相同的行为:
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 方法,
仅使用回调:
$.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!!!!!
关于javascript - CSS动画结束回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948812/