如何在鼠标悬停时立即停止CSS动画?

6

我做了一个CSS动画,包括淡入和淡出一个元素。
我在这里设置了一个fiddle:http://jsfiddle.net/BX78D/(仅限webkit)。

@-webkit-keyframes blink {
    0% {opacity:1;}
    50% {opacity:0;}
    100% {opacity:1;}
}

那部分内容没问题,但以下这部分内容需要帮助: 当用户悬停在该元素上时,我需要动画停止,并使元素立即恢复到100%的不透明度(具有新的背景颜色)。目前,我只能在保持当前不透明度动画的情况下更改背景颜色。是否有人知道如何做到这一点? 解决方案必须是仅使用CSS的方案。由于客户规则的限制,我无法使用JS进行操作。如果不能仅使用CSS完成,则必须放弃整个效果。

1
这是你要找的内容吗?http://jsfiddle.net/BX78D/1/ - dlane
是的,这就是我所缺少的!谢谢。 - andi
3个回答

3

因为你正在使用动画效果 opacity,所以当鼠标悬停在元素上时,需要将其重新设置为100%或1,并确保@keyframes不会运行。

.blink:hover {
    background:red; 
    opacity: 1;
    -webkit-animation-name: none;
    /* should be set to 100% opacity as soon as the mouse enters the box; when the mouse exits the box, the original animation should resume. */
}

JSFiddle


1
只需将-webkit-animation-name覆盖为none
:hover的CSS部分内写入:
-webkit-animation-name: none;

代码片段


0

类似以下的jQuery代码片段应该可以解决问题:

$(".blink").hover(function(){
  if ($(this).is(':animated')) {
      $(this).css('opacity', '1');
      $(this).css('background', 'red');
      $(this).css("-webkit-animation", "none");
      $(this).css("-moz-animation", "none");
      $(this).css("-ms-animation", "none");
      $(this).css("-o-animation", "none");
      $(this).css("animation", "none");
  }
});

上述代码可以重写为:

$(".blink").hover(function(){
  if ($(this).is(':animated')) {
      $(this).css({
          'opacity' : '1',
          'background' : 'red',
          '-webkit-animation' : 'none',
          '-moz-animation' : 'none',
          '-ms-animation' : 'none',
          '-o-animation' : 'none',
          'animation' : 'none'
      });
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接