Как оживить CSS3-анимацию при смене класса - PullRequest
6 голосов
/ 05 января 2012

Итак, у меня есть эти сценарии CSS3

#place.us .level1 { background-position: -100px; background-color: #333; }
#place.gb .level1 { background-position: -100px; background-color: #CCC; }

@-webkit-keyframes place-pop-livel1 { 
    0% { bottom: -100px; } 
    100% { bottom: 30px; }
}
#place .level1 { 
    animation: place-pop-livel1 2s ease-out;
    -moz-animation: place-pop-livel1 2s ease-out; 
    -webkit-animation: place-pop-livel1 2s ease-out; 
}

Когда страница загружается впервые, div имеет #place.us, и анимация работает отлично. Теперь я хочу изменить класс div на 'gb', чтобы сделать его #place.gb с помощью jquery, и как только класс будет изменен, я хочу, чтобы произошла та же анимация.

Мой код jquery прост

$('.change-city').live('click', function(){
    var city = $(this).data('city'); //gb or us
    $('#place').removeClass().addClass(city);
});

Класс изменяется, и на свойство .level1 влияет, как объявлено в CSS, но анимация не происходит. Как убедиться, что анимация происходит?

1 Ответ

5 голосов
/ 05 января 2012

Я бы порекомендовал использовать CSS-переходы, так как они лучше охватывают браузер, ими проще управлять и они лучше откатываются (если браузер не поддерживает переходы, он делает то же самое без анимации).

Ваша проблема может быть решена так:

// after load add the animation
$(".level1").addClass("pop");

// after the animation is done hide it again
$(".level1").bind("webkitTransitionEnd mozTransitionEnd oTransitionEnd msTransitionEnd transitionend", function(){
  $(this).removeClass("pop");
});

$('.change-city').live('click', function(){
    var city = $(this).data('city'); //gb or us
    $('#place').removeClass().addClass(city).find(".level1").addClass("pop");
});

и CSS

#place.us .level1 {background-color: #333; }
#place.gb .level1 {background-color: #CCC; }


#place .level1 {
  position: absolute;
  background-color: #000;
  width: 100px;
  height: 100px;
  bottom: -100px;
  -webkit-transition: bottom 2s ease;
  -moz-transition: bottom 2s ease;
  -o-transition: bottom 2s ease;
  -ms-transition: bottom 2s ease;
  transition: bottom 2s ease;
}


#place .pop {
  bottom: 30px
}

Вы можете проверить jsfiddle здесь: http://jsfiddle.net/EmsXF/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...