21

在很多情况下,我希望动画能够同步执行。特别是当我希望制作一系列连续动画时。

有没有一种简单的方法可以使 jQueryanimate函数调用同步?

我想到的唯一方法是在动画完成时设置一个标志为真并等待这个标志。

4

7 回答 7

28

jQuery 无法制作同步动画。

请记住,JavaScript 在浏览器的 UI 线程上运行。

如果您制作同步动画,浏览器将冻结,直到动画完成。

为什么需要这样做?

您可能应该使用 jQuery 的回调参数并在回调中继续您的方法代码,如下所示:

function doSomething() {
    var thingy = whatever;
    //Do things
    $('something').animate({ width: 70 }, function() {
        //jQuery will call this method after the animation finishes.
        //You can continue your code here.
        //You can even access variables from the outer function
        thingy = thingy.fiddle;
    });
}

这称为闭包。

于 2009-10-20T11:55:36.783 回答
7

我认为你应该看看 jQuery queue()方法。

queue() 的文档不仅解释了 jQuery 动画并没有真正阻塞 UI,而且实际上将它们一个接一个地排队。

它还提供了一种使您的动画和函数调用顺序的方法(这是我对“同步”含义的最佳理解),例如:

$("#myThrobber")
    .show("slow")                 // provide user feedback 
    .queue( myNotAnimatedMethod ) // do some heavy duty processing
    .hide("slow");                // provide user feedback (job's 

myNotAnimatedMethod() { // or animated, just whatever you want anyhow...
    // do stuff
    // ...

    // tells #myThrobber's ("this") queue your method "returns", 
    // and the next method in the queue (the "hide" animation) can be processed
    $(this).dequeue();

    // do more stuff here that needs not be sequentially done *before* hide()
    // 
}  

这对于异步处理来说当然是矫枉过正了。但如果您的方法实际上是一个普通的旧同步 javascript 方法,那可能就是这样做的方法。

希望这会有所帮助,并为我糟糕的英语感到抱歉......

于 2010-04-26T19:36:06.000 回答
2

jQuery 为其 .animate() 方法提供了一个“步骤”回调。您可以使用它来执行同步动画:

jQuery('#blat').animate({
  // CSS to change
  height: '0px'
},
{
  duration: 2000,
  step: function _stepCallback(now,opts) {
    // Stop browser rounding errors for bounding DOM values (width, height, margin, etc.)
    now = opts.now = Math.round(now);

    // Manipulate the width/height of other elements as 'blat' is animated
    jQuery('#foo').css({height: now+'px'});
    jQuery('#bar').css({width: now+'px'});
  },
  complete: function _completeCallback() {
    // Do some other animations when finished...
  }
}
于 2009-12-08T17:53:28.700 回答
1

我同意@SLaks 的观点。您应该为给定的动画使用 jQuery 的回调来创建您的同步动画。您基本上可以为当前动画获取任何内容并将其拆分,如下所示:

$yourClass = $('.yourClass');
$yourClass.animate({
    width: "70%"
}, 'slow', null, function() {
    $yourClass.animate({
        opacity: 0.4
    }, 'slow', null, function() {
        $yourClass.animate({
            borderWidth: "10px"
        });
    });
});
于 2009-10-20T12:57:53.390 回答
0

我遇到了这个http://lab.gracecode.com/motion/ 真的很容易使用并且与 jquery 结合使用效果很好。

编辑 链接似乎死了。如果我正确地跟踪了那些回程存档,则代码位于https://github.com/feelinglucky/motion

于 2010-07-30T14:52:04.143 回答
0

jQuery 可以制作同步动画。看一下这个:

function DoAnimations(){
  $(function(){
    $("#myDiv").stop().animate({ width: 70 }, 500);
    $("#myDiv2").stop().animate({ width: 100 }, 500);
  });
}
于 2011-10-07T15:48:02.043 回答
0

这是我不久前整理的一个模块,用于帮助按顺序运行动画。

用法:

var seq = [
    { id: '#someelement', property:'opacity', initial: '0.0', value:'1.0', duration:500 },
    { id: '#somethingelse', property:'opacity', value:'1.0', duration: 500 }
];

Sequencer.runSequence(seq);

var Sequencer = (function($) {
    var _api = {},
        _seq = {},
        _seqCount = 0,
        _seqCallback = {};

    function doAnimation(count, step) {
        var data = _seq[count][step],
            props = {};

            props[data.property] = data.value

        $(data.id).animate(props, data.duration, function() {
            if (step+1 < _seq[count].length) {
                doAnimation(count, ++step);
            } else {
                if (typeof _seqCallback[count] === "function") {
                    _seqCallback[count]();
                }
            }
        });
    }

    _api.buildSequence = function(id, property, initial, steps) {
        var newSeq = [],
            step = {
                id: id,
                property: property,
                initial: initial
            };

        $.each(steps, function(idx, s) {
            step = {};
            if (idx == 0) {
                step.initial = initial;
            }
            step.id = id;
            step.property = property;
            step.value = s.value;
            step.duration = s.duration;
            newSeq.push(step);
        });

        return newSeq;
    }

    _api.initSequence = function (seq) {
        $.each(seq, function(idx, s) {              
            if (s.initial !== undefined) {
                var prop = {};
                prop[s.property] = s.initial;
                $(s.id).css(prop);
            }            
        });
    }

    _api.initSequences = function () {
        $.each(arguments, function(i, seq) {
            _api.initSequence(seq);
        });
    }

    _api.runSequence = function (seq, callback) {
        //if (typeof seq === "function") return;
        _seq[_seqCount] = [];
        _seqCallback[_seqCount] = callback;

        $.each(seq, function(idx, s) {

            _seq[_seqCount].push(s);
            if (s.initial !== undefined) {
                var prop = {};
                prop[s.property] = s.initial;
                $(s.id).css(prop);
            }

        });


        doAnimation(_seqCount, 0);
        _seqCount += 1;
    }

    _api.runSequences = function() {
        var i = 0.
            args = arguments,
            runNext = function() {
                if (i+1 < args.length) {
                    i++;
                    if (typeof args[i] === "function") {
                        args[i]();
                        runNext();
                    } else {
                        _api.runSequence(args[i], function() {
                            runNext();
                        });
                    }
                }
            };

        // first we need to set the initial values of all sequences that specify them
        $.each(arguments, function(idx, seq) {
            if (typeof seq !== "function") {
                $.each(seq, function(idx2, seq2) {
                    if (seq2.initial !== undefined) {
                        var prop = {};
                        prop[seq2.property] = seq2.initial;
                        $(seq2.id).css(prop);
                    }
                });
            }

        });

        _api.runSequence(arguments[i], function (){
            runNext();
        });

    }

    return _api;
}(jQuery));
于 2011-10-07T16:06:00.597 回答