2014-02-11 104 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/