2014-02-11 105 views
0

我一直在玩JS + CSS动画第一次。 我想旋转一个div(或独立一群人),这些随机因素:随机无限旋转动画与jQuery

  • 随机方向
  • 随机度
  • 随着随机暂停

我设法收集这个脚本,运行良好。它旋转使用id = “方形” 无穷一个div,进入[随机]方向,通过[随机]度

function redo() { 
    $.fn.animateRotate = function(angle, duration, easing, complete) { 
      return this.each(function() { 
      var $elem = $(this); 

      $({deg: 0}).animate({deg: angle}, { 
       duration: duration, 
       easing: easing, 
       step: function(now) { 
        $elem.css({ 
         transform: 'rotate(' + now + 'deg)' 
        }); 
       }, 
       complete: complete //|| $.noop 
      }); 
     }); 
    }; 
    plusOrMinus = Math.random() < 0.5 ? -1 : 1; 
    randAngle = Math.floor(Math.random()*70+30) * plusOrMinus; 
    randDelay = Math.floor(Math.random()*3000+2000); 
    $('#square').animateRotate(randAngle); 
    timer = setTimeout(function() { redo(); },randDelay); 
} 

redo(); 

http://jsfiddle.net/NWLVY/1

现在,我一直有几个困难:

  1. 我想将多个元素传入此循环,并且我希望它们独立行为。我不介意他们是否都有同一个班级,或者我只需要写多行来执行每一个班级。不会有太多。
  2. 此旋转不会从最后一个角度继续。它不断跳回来。我无法弄清楚如何解决这个问题。
  3. 我似乎无法通过任何缓解选项,如swinglinear,也没有任何其它选项,例如durationcomplete

回答

1

解决。

我用了一个稍微不同的脚本,但它现在可以工作。 我加入过渡和动画系的旋转元件的CSS,

transition:2s; 
animation:ease-in-out; 

那些似乎已经固定的锯齿状纺纱的问题,让我增加一些宽松。 然后我用了一个包装函数来传递函数中的不同元素。

<Script> 
function rotate (elementID) { 

    var $rota = $(elementID), 
     degree = 0, 
     timer; 

    function spin() {  
     $rota.css({ transform: 'rotate(' + degree + 'deg)'}); // rotate element 
     plusOrMinus = Math.random() < 0.5 ? -1 : 1;  // random spin direction 
     randAngle = Math.floor(Math.random()*70+50) * plusOrMinus; // random degrees 
     randDelay = Math.floor(Math.random()*1000+2000); //random delay 
     timer = setTimeout(function() { // set delay 
      degree += randAngle; // add random degree to current variable 
      spin(); // loop it 
     },randDelay); 
    } 

    spin(); // start first spin for element 

}; 

rotate ('#square'); // run it 
rotate ('#square2'); // run it again 

</script> 

这是在工作http://jsfiddle.net/NWLVY/2/