javascript - CSS动画结束回调

标签 javascript jquery css promise

我有一个小的 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 会将 animatefadeOut 放入 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 方法,
仅使用回调:

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!!!!!

关于javascript - CSS动画结束回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948812/

相关文章:

jquery - 选择 ID 中带有特殊字符的元素

jquery - 允许用户将选项添加到自动完成列表(预先输入 Bootstrap )

html - 我可以在 CSS 中创建一个底部有弧形的 div 吗?

javascript - Safari 与 Chrome 兼容性问题

Javascript - 如何让filter()返回匹配结果

javascript - JSLint 错误 - 预期为 '/',但看到的是 ''

javascript - 如何从 JavaScript 中的 URL 获取基域

javascript - tfjs-node-gpu Windows 上的 ELF header 无效

jquery - 在 Firefox 上使用 jquery .hover 和 map 时遇到问题

html - 如何使div宽度适合div内的表格?