Петлевые функции, анимация вращения css

0

Я пытаюсь создать функцию, которая анимирует переход, а затем, как только это сделает это, оживит вращение назад к своей начальной точке и циклически это сделает.

У меня есть только следующее: я не могу заставить анимацию работать или возвращаться к умолчанию?

http://jsfiddle.net/QfeC2/

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

setTimeout(function() { drunk(); }, 2000);
Теги:

3 ответа

0
Лучший ответ

Если вы анимируете css, почему бы не использовать чистый CSS? Вы можете обернуть свойство анимации в классе и переключить этот класс в 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);}
}

Обновленная скрипка

1

.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

  • 0
    Спасибо @Anton, я хочу, чтобы он вращался плавно, однако
  • 0
    @Liam Вы хотели, чтобы это выглядело так? jsfiddle.net/QfeC2/8
Показать ещё 1 комментарий
0

см. обновленную скрипту: 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);

ОБНОВИТЬ

поворачивать назад после каждого цикла:

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);
  • 0
    Это в соответствии с тем, что я после @JFit, только я не могу заставить его вращаться и затем вращаться назад, он вращается и затем возвращается к своему положению по умолчанию в 1 большом прыжке
  • 0
    ааа ладно .. Джимми несколько секунд, чтобы обновить.
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню