使用自定义jQuery动画时的.done()回调

时间:2017-08-18 12:33:20

标签: javascript jquery jquery-animate deferred custom-function

我正在使用以下功能为幻灯片设置动画,就像slideUp()slideDown()一样:

(function($) {    
    jQuery.fn.slideLeftHide = function(speed, callback) {
      this.animate({
        width: "hide",
        paddingLeft: "hide",
        paddingRight: "hide",
        marginLeft: "hide",
        marginRight: "hide"
      }, speed, callback);
    }

    jQuery.fn.slideLeftShow = function(speed, callback) {
      this.animate({
        width: "show",
        paddingLeft: "show",
        paddingRight: "show",
        marginLeft: "show",
        marginRight: "show"
      }, speed, callback);
    }
})(jQuery);

问题是,我想在动画结束后只调用一次函数。  我试过这样做:

$(".item").slideLeftHide(function() {
    $(this).remove();

}).done(function() {
    $(".tab").each(function() {
        $(this).attr('data-status', 'success');
    });
});

当我执行此代码时,收到一条错误消息Cannot read property 'done' of undefined.then()代替.done()也是如此。

我该如何解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

(function ($) {
    function slideLeftBinder(action) {
        return function () {
            var i = 0,
                speed = ((Number(arguments[i]) === parseFloat(arguments[i]) && !isNaN(arguments[i])) || undefined) && arguments[i++],
                callback = (typeof arguments[i] === 'function' || undefined) && arguments[i++],
                self = this;

            return new Promise(function (resolve) {
                var completed = 0;

                self.animate({
                    width: action,
                    paddingLeft: action,
                    paddingRight: action,
                    marginLeft: action,
                    marginRight: action
                }, {
                    duration: speed,
                    complete: callback,
                    always: function() {
                        if (self.length === ++completed) {
                            resolve(self);
                        }
                    }
                });
            });
        };
    }

    jQuery.fn.slideLeftHide = slideLeftBinder('hide');
    jQuery.fn.slideLeftShow = slideLeftBinder('show');
})(jQuery);

像这样使用:

$(".item")
    .slideLeftHide(function() {
        $(this).remove();
    })
    .then(function(selector) {
        console.log('selector: ', selector);
        $(".tab").attr('data-status', 'success');
    });