完成后反转CSS动画

时间:2018-02-09 15:45:51

标签: jquery css-animations

我有一个CSS动画,我想做的是在初始动画完成后让动画反转。这是我到目前为止所尝试的内容:

$(window).load(function () {
  $('.animation-container').addClass('animate');
});

$(function() {
    var animationCount = 0;
    $(".animation-container").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function () {
        animationCount++
        if (animationCount === 2) {
          $('.animation-container').addClass('reverse');
        }
    });
});
.animation-container > div {
  display:block;
  background:#000;
  width:20px;
  height:30px;
}

.animation-container.animate {
  animation:rotateOuter 2s ease-in-out;
  animation-fill-mode: forwards;
  animation-delay: 2s;
}
  .animation-container.reverse {
    animation:rotateOuter 2s ease-in-out;
    animation-direction: reverse;
  }

.animation-container.animate .top {
  animation:rotateInner 2s ease-in-out;
  animation-fill-mode: forwards;
}
  .animation-container.reverse .top {
    animation:rotateInner 2s ease-in-out;
    animation-direction:reverse;
  }

@keyframes rotateOuter {
    0% {
        transform:rotate(0deg);
    }
    100% {
        transform:rotate(-20deg);
    }
}

@keyframes rotateInner {
    0% {
        transform:rotate(0deg);
    }
    100% {
        transform:rotate(-30deg);
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="animation-container">
  <div class="top"></div>
  <div class="bottom"></div>
</div>

这里的想法是在第一个动画完成后向元素添加一个带有animation-direction:reverse;的类,不幸的是它没有按计划工作,只是回到默认的非动画状态。

1 个答案:

答案 0 :(得分:2)

让整个事物成为一个动画。关键是修改动画帧和延迟,以便它符合您的要求

$('.animation-container').addClass('animate');

&#13;
&#13;
$(function() {
  $('.animation-container').addClass('animate');

});
&#13;
.animation-container > div {
  display: block;
  background: #000;
  width: 20px;
  height: 30px;
}

.animation-container.animate {
  animation: rotateOuter 4s ease-in-out;
  animation-fill-mode: forwards;
  animation-delay: 1s;
}


.animation-container.animate .top {
  animation: rotateInner 4s ease-in-out;
  animation-fill-mode: forwards;
}

@keyframes rotateOuter {
  0% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(-20deg);
  }
  50% {
    transform: rotate(0deg);
  }
  75% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes rotateInner {
  0% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(-30deg);
  }
  50% {
    transform: rotate(-30deg);
  }
  75% {
    transform: rotate(-30deg);
  }
  100% {
    transform: rotate(0deg);
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="animation-container">
  <div class="top"></div>
  <div class="bottom"></div>
</div>
&#13;
&#13;
&#13;