简体   繁体   English

jQuery同时在同一对象上循环播放动画

[英]jQuery loop animations on same object at the same time

Is it possible to animate the same object with different speeds and starting at the same time? 是否可以以不同的速度同时启动同一物体的动画?

function loop_horiz(direction){
    var d = (direction == 1) ? '+' : '-';
    $('.op').animate({ left: d + '200' },
     4000, function() { loop_horiz(direction * (-1)) });
}

function loop_vert(direction){
    var d = (direction == 1) ? '+' : '-';
    $('.op').animate({ bottom: d + '200' },
    2000, function() { loop_vert(direction * (-1)) });
}

loop_horiz(1);
loop_vert(1)

Normally when animating an object with jQuery, the animation is added to the queue for that object. 通常,使用jQuery为对象设置动画时,会将动画添加到该对象的队列中。 When previous animations have ended, the animation starts running. 先前的动画结束后,动画将开始运行。 Your code above does exactly that, animates horizontally, then vertically. 上面的代码正是这样做的,先进行水平动画,然后进行垂直动画。

This behavior can be overwritten by the use of the queue option of the animation (set it to false). 通过使用动画的queue选项(将其设置为false)可以覆盖此行为。

function loop_horiz(direction) {
    var d = (direction == 1) ? '+' : '-';
    $('.op').animate({
        left: d + '200'
    }, {
        queue: false,
        duration: 4000,
        done: function () {
            loop_horiz(direction * (-1))
        }
    });
}

function loop_vert(direction) {
    var d = (direction == 1) ? '+' : '-';
    $('.op').animate({      
        bottom: d + '200'
    }, {
        queue: false,
        duration: 2000,
        done: function () {
            loop_vert(direction * (-1))
        }
    });

}

loop_horiz(1);
loop_vert(1)

Another (uglier) possibility is to merge the animations, but it would require you to split the horizontal animation in two for half the distance running over 2s. 另一种(更丑陋的)可能性是合并动画,但是这要求您将水平动画一分为二,并且将距离移动超过2秒。

http://api.jquery.com/animate/ http://api.jquery.com/animate/

Even better, with queue as string you can add the animations to different queues. 更好的是,使用队列作为字符串,您可以将动画添加到不同的队列。 Same code as above, but using different queues for vertical and horizontal animation: 与上面相同的代码,但对垂直和水平动画使用不同的队列:

function loop_horiz(direction) {
    var d = (direction == 1) ? '+' : '-';
    $('.op').animate({
        left: d + '200'
    }, {
        queue: 'horizontal',
        duration: 4000,
        done: function () {
            loop_horiz(direction * (-1))
        }
    }).dequeue('horizontal');
}

function loop_vert(direction) {
    var d = (direction == 1) ? '+' : '-';
    $('.op').animate({
        bottom: d + '200'
    }, {
        queue: 'vertical',
        duration: 2000,
        done: function () {
            loop_vert(direction * (-1))
        }
    }).dequeue('vertical');

}

loop_horiz(1);
loop_vert(1)

DEMO: http://jsfiddle.net/Uewzc/1/ 演示: http : //jsfiddle.net/Uewzc/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM