循环函数,动画css旋转

我试图创建一个动画转换动画的函数,然后一旦它完成此操作,将旋转动画回到它的起始点并无限循环。

我有以下只有我不能让动画工作,也没有返回默认值?

http://jsfiddle.net/QfeC2/

function drunk(){ $('div').css({'-webkit-transform':'rotate(1deg)'}); $('div').delay(4000).css({'-webkit-transform':'rotate(0deg)'}); } setTimeout(function() { drunk(); }, 2000); 

如果你用css制作动画,为什么不使用纯CSS呢? 您可以将动画属性包装在Class中,并在JS中切换该类。

 div { -webkit-animation:anim 2s ease infinite; } @-webkit-keyframes anim { 0 {-webkit-transform:rotate(0deg);} 50% {-webkit-transform:rotate(1deg);} 100% {-webkit-transform:rotate(0deg);} } 

更新小提琴

.delay()仅在使用jquery动画时有效,必须使用setTimeout

 function drunk() { $('div').css({ '-webkit-transform': 'rotate(1deg)' }); setTimeout(function () { $('div').css({ '-webkit-transform': 'rotate(0deg)' }); }, 4000); } setTimeout(function() { drunk(); }, 2000); 

DEMO

使用setInterval进行连续循环

 setInterval(function(){drunk();},8000); 

DEMO

看到你更新的小提琴: http : //jsfiddle.net/QfeC2/3/

 function AnimateRotate(angle) { // caching the object for performance reasons var $elem = $('div'); // we use a pseudo object for the animation // (starts from `0` to `angle`), you can name it as you want $({deg: 0}).animate({deg: angle}, { duration: 2000, step: function(now) { // in the step-callback (that is fired each step of the animation), // you can use the `now` paramter which contains the current // animation-position (`0` up to `angle`) $elem.css({ transform: 'rotate(' + now + 'deg)' }); }, complete: function(){ AnimateRotate(360); } }); } AnimateRotate(360); 

UPDATE

每个周期后旋转回来:

http://jsfiddle.net/QfeC2/9/

 var boolDirection = true; function AnimateRotate(angle) { // caching the object for performance reasons var $elem = $('div'); // we use a pseudo object for the animation // (starts from `0` to `angle`), you can name it as you want $({deg: 0}).animate({deg: angle}, { duration: 2000, step: function(now) { // in the step-callback (that is fired each step of the animation), // you can use the `now` paramter which contains the current // animation-position (`0` up to `angle`) $elem.css({ transform: 'rotate(' + now + 'deg)' }); }, complete: function(){ if(boolDirection) { AnimateRotate(-360); boolDirection = false; } else { AnimateRotate(360); boolDirection=true; } } }); } AnimateRotate(360);