动画方法

时间:2015-08-06 16:46:37

标签: jquery animation

我正在使用下面的动画来生成在日历中切换到下个月或上个月的效果。在可见的情况下,我使用了if-else语句来获得适当的动画效果;我怎么能在这里使用我的回调函数,以便在动画完成后产生某些效果。

$('.open').each(function (index) {

    if ($('#' + (firstDay + index)).html() < 10) {
        $('#' + (firstDay + index)).animate({
            top: pos[firstDayPrevious + index].top,
            left: pos[firstDayPrevious + index].left + 7,
        }, (400 + (25 * index)));

    } else {
        $('#' + (firstDay + index)).animate({
            top: pos[firstDayPrevious + index].top,
            left: pos[firstDayPrevious + index].left,
        }, (400 + (25 * index)));
    }

});

2 个答案:

答案 0 :(得分:1)

您可以从jQuery对象获取动画承诺,并在所有相关动画队列(即所有always()元素)都为空时使用$('.open')进行回调。

e.g。

$('.open').each(function (index) {

    if ($('#' + (firstDay + index)).html() < 10) {
        $('#' + (firstDay + index)).animate({
            top: pos[firstDayPrevious + index].top,
            left: pos[firstDayPrevious + index].left + 7,
        }, (400 + (25 * index)));

    } else {
        $('#' + (firstDay + index)).animate({
            top: pos[firstDayPrevious + index].top,
            left: pos[firstDayPrevious + index].left,
        }, (400 + (25 * index)));
    }

}).promise().always(function(){
    // Do stuff here on completion of all animations
});

说明:

  • 您可以对动画承诺使用done,但是,如果动画永远不会启动*(例如,如果它已经处于最终状态),那么它将不会触发。始终使用always():)
  • 您的代码可以通过几种方式简化和加快。例如使用临时变量而不是重新运行jQuery选择器。

e.g。

$('.open').each(function (index) {
    var $control = $('#' + (firstDay + index);
    if ($control.html() < 10) {
        $control.animate({
            top: pos[firstDayPrevious + index].top,
            left: pos[firstDayPrevious + index].left + 7,
        }, (400 + (25 * index)));

    } else {
        $control.animate({
            top: pos[firstDayPrevious + index].top,
            left: pos[firstDayPrevious + index].left,
        }, (400 + (25 * index)));
    }

}).promise().always(function(){
    // Do stuff here on completion of all animations
});

进一步减少到:

$('.open').each(function (index) {
    var $control = $('#' + (firstDay + index);
    $control.animate({
        top: pos[firstDayPrevious + index].top,
        left: pos[firstDayPrevious + index].left + ($control.html() < 10) ? 7 : 0,
        }, (400 + (25 * index)));
    }
}).promise().always(function(){
    // Do stuff here on completion of all animations
});

答案 1 :(得分:0)

根据jQuery文档:http://api.jquery.com/animate/

.animate( properties [, duration ] [, easing ] [, complete ] )

所以这是:

$('#' + (firstDay + index)).animate({
    top: pos[firstDayPrevious + index].top, 
    left: pos[firstDayPrevious + index].left + 7,
},(400 + (25 * index)), function()
{
    // callback function
});
相关问题