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



我使用以下函数来像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().

我该如何解决这个问题?

谢谢!

(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');
});

最新更新