CSS @keyframes动画在悬停时闪烁

3

Demo GIF

当我创建一个@keyframes动画并将其分配给悬停在图像上时,它会在随机时间闪烁。如您在GIF中所见,它只能正常工作几次。

我已经尝试了以下所有方法,并为每个前缀供应商:

backface-visibility: hidden;

animation-fill-mode: forwards;

transform-style: preserve-3d;

为什么会发生这种情况,如何解决?

这可以在this jsfiddle中复制。


一旦你移动鼠标,它就不再停留在图像上。它会自动移回原位。由于延迟,你不会一直看到它闪烁,但基本上你可以期望它在每个奇数渲染步骤中向右移动,在每个偶数渲染步骤中向左移动。 - Randy
出现了几个小时的闪烁问题,使用“transform-style: preserve-3d;”解决了。非常感谢。 - m4heshd
3个回答

3
问题是图像会远离你的鼠标,导致失去其动画效果。图示(#表示鼠标光标):
首先,你用鼠标对其进行聚焦并使其动起来:
--------
|   #  |
--------

下一次渲染时,由于失去了鼠标焦点,因此失去了其动画效果。
         -------
    #    |     |
         -------

下一次渲染,它会返回其原始状态,因为它不再具有:hover状态:
--------
|   #  |
--------

再次强调,它将会有动画效果:

         -------
    #    |     |
         -------

如果您将鼠标悬停在父元素上,它将保持焦点在该父元素上。然后,您可以使用parent:hover > child { animate }
----------------------
|     -----          |
|     | # |          |
|     -----          |
----------------------

----------------------
|           -----    |
|        #  |   |    |
|           -----    |
----------------------

解决这个问题的一种方法是在父元素上设置鼠标悬停效果:

.imgwrapper > img {
  height: 100px;
  background-color: red;
  backface-visibility: hidden;
  animation-fill-mode: forwards;
  transform-style: preserve-3d;
  display:inline-block;
}

.imgwrapper:hover > img {
  animation: move 1s;
}

@keyframes move {
  0% {
    transform: translateX(100px);
  }
  
  100% {
    transform: translate(0);
  }
}
<div class="imgwrapper">
  <img src="http://place-hold.it/300x500?text=New Text&bold"/>
</div>


1
作为@Randy在评论中所解释的,一旦你移动鼠标,它就不再停留在图像上了,这就导致了bug。你可以通过将图像包装在<div>中,并在<div>上使用:hover来简单解决此问题。

以下是一个示例代码:

div {
  display: inline-block;
}

img {
  height: 100px;
  background-color: red;
  backface-visibility: hidden;
  animation-fill-mode: forwards;
  transform-style: preserve-3d;
}

div:hover img {
  animation: move 1s;
}

@keyframes move {
  0% {
    transform: translateX(100px);
  }
  100% {
    transform: translate(0);
  }
}
<div>
  <img src="http://www.stickpng.com/assets/images/584181fda6515b1e0ad75a33.png" />
</div>
<p>
  Sometimes a strange flicker occurs on hover.
</p>

希望这对你有所帮助。

-2
使用图像的过渡速度,以获得平滑的效果。使用以下代码。
img{
    -webkit-transition: .3s ease-out;
    transition: .3s ease-out;
}

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