jquery when()与动画

时间:2014-09-09 13:26:19

标签: jquery jquery-animate

    $.when(
        $('#el1').animate({ left: '400px' }, { duration: 1000}),
        $('#el2').animate({ left: '600px' }, { duration: 1000}))
.done(function() { ...}).fail(function(){ ...});

当用户调整停止这些动画的浏览器时,我还异步触发了事件:

$('#el1').stop(true,false);
$('#el2').stop(true,false);

所以我希望。fail()方法应该被执行,但它不是,.done()方法被执行。

是否有某种方法以某种方式强制.fail()方法?

我知道我可以在不使用.when/.done的情况下实现这一目标,但我需要这个,而且我实际上需要理解这一点。

1 个答案:

答案 0 :(得分:3)

如果发生reject,你可以resize保持另一个承诺,解决这个问题(没有双关语意)。

// promise that will reject on window resize (probably needs to 
// be debounced to prevent multiple calls to .reject)

var completed = $.Deferred();
$(window).on('resize', completed.reject);

// this would be the original code, dependent on both the animations
// **and** the new promise.  As soon as the promise is rejected this
// code *should* drop to .fail immediately (and incidentally stop
// the animations)

$.when($('#el1, #el2'), completed).done(function() {
     ...
}).fail(function() {
    $('#el1, #el2').stop(true, false);
});

// new .when, that only depends on the two animations.  It'll fire
// whether the animations complete or not, but should do nothing if
// the promise was already rejected because of the resize.

$.when($('#el1, #el2')).done(completed.resolve);

请参阅http://jsfiddle.net/alnitak/ejm7pkzd/