1

我有一个 div 元素来回旋转一定次数,使用以下代码:

插入:

<script type="text/javascript" src="http://jqueryrotate.googlecode.com/svn/trunk/jQueryRotate.js"></script>

代码:

$(document).ready(function(){
var rotation = function (times) {
var el = $("#pencil");
if(typeof times == 'number'){
    el.data('repeatRotation',times);
} else {
    times = el.data('repeatRotation')-1;
    el.data('repeatRotation',times);
}
if(times > 0){
    $("#pencil").rotate({
        angle: 0,
        animateTo: 2,
        duration: 200,
        callback: rotationBack
    });
}
}
var rotationBack = function () {
$("#pencil").rotate({
    angle: 0,
    animateTo: -2,
    duration: 200,
    callback: rotation
});
}
rotation(10);
});

我真正想要的是 div 元素在 5 秒延迟后开始旋转。我尝试将通常的 .delay(5000) 添加到上面的代码中,如下所示,但这似乎没有什么区别,代码在页面加载后仍然立即执行:

if(times > 0){
    $("#pencil").delay(5000).rotate({
        angle: 0,
        animateTo: 2,
        duration: 200,
        callback: rotationBack
    });

有谁知道为什么 .delay(5000) 在这种情况下不起作用?

4

2 回答 2

1

.delay()仅适用于队列中的对象。如果它不适用于该插件,则意味着他们没有以添加到 jQuery 队列的方式实现动画。setTimeout在使用中添加此功能很容易

if (times > 0) {
    setTimeout(function () {
        $("#pencil").rotate({
            angle: 0,
            animateTo: 2,
            duration: 200,
            callback: rotationBack
        });
    }, 5000);

将延迟添加到第一次轮换中,将您的代码从

rotation(10);

setTimeout(function(){
    rotation(10);
},5000);
于 2013-09-08T13:13:05.010 回答
1

原因delay对您不起作用是因为最初动画队列中没有任何东西可以延迟。

要解决此问题,您需要将.rotate呼叫排队:

$('#pencil').delay(4000).queue(function(){

  $(this).rotate({
    angle: 0,
    animateTo: 2,
    duration: 200,
    callback: rotationBack
  });

});

看看this jsbin一个例子。

也看看这个问题How to delay jquery animation

于 2013-09-08T13:18:11.000 回答