CSS:暂停前完成动画

时间:2018-05-28 22:09:53

标签: css css3 css-animations

我在图标上有一个稳定的弹跳动画,每隔一段时间就会重复一次。当我将鼠标悬停在图标上时,我希望动画在暂停之前顺利完成。

然而,尽我所能,我发现这令人惊讶地难以做到。元素暂停到位,或者到完成状态的过渡不顺畅。

  • animation-play-state: paused会冻结动画,但我希望它先完成
  • animation: none删除将元素重置为默认位置的动画,但不是平滑过渡
  • transition: <stuff>似乎没有将图标平滑过渡到其默认状态
  • animation-iteration-count: 1悬停行为不一致,有时做我想做的事,其他时候不做

如何设置它,以便当我将鼠标悬停在图标上时,动画会在暂停之前首先完成?我觉得我错过了一些显而易见的东西,但已经遇到了多个死胡同。

以下是我正在使用的大致代码。

@keyframes bounce {
  0%   { right: 0; }
  10%  { right: 0.5em; }
  20%  { right: 0; }
  30%  { right: 0.5em; }
  40%  { right: 0; }
  100% { right: 0; }
}

.container {
  padding: 2rem;
}

.icon {
  position: relative;
  animation-name: bounce;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

.container:hover .icon {
  animation-play-state: paused;
}
<div class="container">
  <span class="icon">&gt;</span> Some text
</div>

2 个答案:

答案 0 :(得分:0)

我认为获得所需内容的最佳方式是在animation-iteration-count: 1;状态下使用animation-play-state: paused;代替hover,因此不会重复动画。

@keyframes bounce {
  0%   { right: 0; }
  10%  { right: 0.5em; }
  20%  { right: 0; }
  30%  { right: 0.5em; }
  40%  { right: 0; }
  100% { right: 0; }
}

.container {
  padding: 2rem;
}

.icon {
  position: relative;
  animation-name: bounce;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.container:hover .icon {
  animation-iteration-count: 1;
}
<div class="container">
  <span class="icon">&gt;</span> Some text
</div>

答案 1 :(得分:0)

正如已经提到的,我不认为这在css中是可能的。我和jQuery一起使用了一个解决方案。弹跳动画现在是一个单独的类,它被添加到图标中。在动画结束时(在第一行bind()中检测到)我删除了类,只有在容器没有悬停时再添加它(将其添加回来,使用setTimeOut,将再次启动动画)。

如果容器正在悬停,则不会再次添加弹跳类,但是您会看到另一个事件监听器检查&#34; mouseout&#34;在容器上,这将把类重新添加。

以下是片段:

&#13;
&#13;
$(".icon").bind("webkitAnimationEnd mozAnimationEnd animationEnd", function() {
    $(this).removeClass("bouncing");
    
    //if hovering, don't repeat
    if ($(".container").is(":hover")) return;
    
    //else, repeat. setTimeout is necessary for animation to take.
    setTimeout(function () {
        $(".icon").addClass("bouncing");
    });
});

$(".container").mouseout(function() {
   $(".icon").addClass("bouncing");
});
&#13;
@keyframes bounce {
  0%   { right: 0; }
  10%  { right: 0.5em; }
  20%  { right: 0; }
  30%  { right: 0.5em; }
  40%  { right: 0; }
  100% { right: 0; }
}

.container {
  padding: 2rem;
}

.icon {
  position: relative;
}

.bouncing {
  animation-name: bounce;
  animation-duration: 4s;
  animation-iteration-count: 1;
 }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <span class="icon bouncing">&gt;</span> Some text
</div>
&#13;
&#13;
&#13;