You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为jQuery自定义高度动画函数添加可链式调用的完成回调?

实现链式调用的动画完成回调

下面提供两种可行的实现方式,满足你通过链式调用afterCompletion添加自定义回调的需求:

方案一:自定义回调队列管理

这种方式直接在函数内部维护回调数组,动画完成时批量执行:

function animateHeight(element, height, duration) {
    const completionCallbacks = [];

    element.animate(
        { "height": height + 'px' },
        {
            duration: duration,
            easing: 'easeInOutSine',
            complete: function() {
                // 遍历执行所有注册的回调,保证this指向动画元素
                completionCallbacks.forEach(callback => callback.call(this));
            }
        }
    );

    return {
        afterCompletion: function(callback) {
            if (typeof callback === 'function') {
                completionCallbacks.push(callback);
            }
            return this; // 返回自身,支持链式添加多个回调
        }
    };
}

// 调用示例
function x() {    
    animateHeight(container, 300, 450)
        .afterCompletion(function(){
            // 自定义逻辑1
            console.log("动画完成,执行逻辑1");
        })
        .afterCompletion(function(){
            // 可以链式添加多个回调
            console.log("动画完成,执行逻辑2");
        });
}

方案二:基于jQuery Deferred/Promise实现

利用jQuery的Deferred对象封装动画流程,同时扩展自定义方法:

function animateHeight(element, height, duration) {
    const deferred = $.Deferred();

    element.animate(
        { "height": height + 'px' },
        {
            duration: duration,
            easing: 'easeInOutSine',
            complete: function() {
                deferred.resolve(this); // 动画完成时传入元素对象resolve
            },
            fail: function() {
                deferred.reject(this); // 处理动画失败场景
            }
        }
    );

    // 给Promise添加自定义的afterCompletion方法
    const animationPromise = deferred.promise();
    animationPromise.afterCompletion = function(callback) {
        this.done(callback);
        return this; // 支持链式调用
    };

    return animationPromise;
}

// 调用示例
function x() {    
    animateHeight(container, 300, 450)
        .afterCompletion(function(){
            // 自定义逻辑1
            console.log("动画完成");
        })
        .done(function(element){
            // 也可以使用原生Promise方法
            console.log("动画完成的元素:", element);
        });
}

为什么你之前的方案没成功?

  • 直接用$.when().done():jQuery的animate返回的是jQuery对象而非Promise,$.when会把jQuery对象视为已完成的状态,导致回调立刻执行,而非等待动画结束。
  • 直接使用async/await:同样需要函数返回标准的Promise对象,未封装Deferred的情况下无法正确等待动画完成。

内容的提问来源于stack exchange,提问作者Bachir Messaouri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:35:44