【问题标题】:CSS3 Animation repeating again and againCSS3动画一遍又一遍地重复
【发布时间】:2015-02-14 17:59:27
【问题描述】:

我正在尝试编写一个动画,使.hint div 在悬停时消失。

这是我尝试过的live demo
但是,即使在最后添加了animation-iteration-count:1; 之后,动画也会一次又一次地继续播放。 Codepen 使用 prefixfree.js,所以我的代码中没有使用供应商前缀。

如何让动画仅在 1 次迭代后停止?

编辑

当光标不在 .hint 上方时,我希望它保持 opacity:0。

【问题讨论】:

  • 你的意思是当它仍然悬停时你希望它保持在opacity: 0

标签: html css animation css-animations


【解决方案1】:

您应该将动画的填充模式设置为forwards。这将使动画保持最后一个 keyframe 执行的状态,即 (opacity: 0;)

animation-fill-mode: forwards;

如果您希望它保持在opacity: 0;,即使鼠标在一次悬停后离开元素,请为opacity: 0; 添加一个类,如下所示,并使用jQuery 将其附加到元素onmouseleave

另外,请记住,在这种情况下,您不能使用 CSS hover,因为如果指定了 :hover 规则,即使 opacity0 并且鼠标移动到元素所在的位置上,它也会触发动画到过。相反,您应该将class 设置为hover,并且只将它附加到元素上,就像我在下面使用jQuery 显示的那样。

$(document).ready(function() {
  $('.hint').on('mouseout', function() {
    $('.hint').addClass('alreadyHovered');
  });
  $('.hint').on('mouseover', function() {
    if (!($('.hint').hasClass('alreadyHovered'))) {
      $('.hint').addClass('hover');
    }
  });
});
@-webkit-keyframes vanish {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
@-moz-keyframes vanish {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
@keyframes vanish {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
.hint {
  width: 20%;
  background-color: #E51400;
  position: fixed;
  top: 10%;
  right: 10px;
  border-width: 2px;
  padding: 1em;
  color: white;
}
.hover {
  -webkit-animation-name: vanish;
  -moz-animation-name: vanish;
  animation-name: vanish;
  -webkit-animation-duration: 2s;
  -moz-animation-duration: 2s;
  animation-duration: 2s;
  -webkit-animation-fill-mode: forwards;
  -moz-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
  -webkit-animation-iteration-count: 1;
  -moz-animation-iteration-count: 1;
  animation-iteration-count: 1;
}
.alreadyHovered {
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hint">Hello</div>

【讨论】:

  • 奇怪。我不使用铬。在 Opera 15、IE10 和 Firefox 23 中确实如此。
  • @svineet:我在 Chrome 31(开发版)中进行了测试,它也可以工作。
  • 它对我有用(Firefox 24)!显然,animation-fill-mode: both; 似乎也可以工作,但我不知道为什么。根据developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode 的说法,这仍然是一项“实验性技术”,所以,也许你不应该过分依赖它在所有浏览器中工作?
  • @cars10:是的,caniuse 说动画在带有 -webkit 前缀的 Chrome 中确实有效。但正如 cmets 中的 OP 所示,这支笔不需要。
  • @svineet:没关系,伙计 :) 不要难过,我们所有人都会遇到这种情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 2021-07-05
相关资源
最近更新 更多