CSS Keyframe Animations on Hover - Animation Resetting with Mouse Movement

谁都会走 提交于 2019-12-24 07:01:29

问题


Please see the code below for a simple keyframe animation on hover.

.behind {
  width: 200px;
  height: 200px;
  background: red;
  position: absolute;
}

.infront {
  width: 200px;
  height: 200px;
  background: blue;
  position: absolute;
}

@keyframes fadeOutLeft {
  from {
    opacity: 1;
  }

  to {
    opacity: 0;
    transform: translate3d(-100%, 0, 0);
  }
}

.infront:hover {
  animation: fadeOutLeft 2s;
}
<div class="behind"></div>
<div class="infront"></div>

This looked to be working on hover, however when moving the mouse even slightly, the animation will restart.

Here is a short video of the issue that I am describing:

https://app.hyfy.io/v/ab7AjpMoXbU/

Is there any way that I can stop the animation from resetting with mouse movement on the element but still have the animation play again when the mouse has left and re-entered? I'm unable to use JavaScript in this particular instance.

Thank you for your wisdom in advance.


回答1:


What's causing the issue is that the hover is applied on the infront div, so when you take the cursor out of that div it stops.

You can fix it by wraping the two divs(infront/behind) inside a div and call hover on the wraper

.wraper:hover .infront {
  animation: fadeOutLeft 2s;
}

See code snippet:

.behind {
  width: 200px;
  height: 200px;
  background: red;
  position: absolute;
}

.infront {
  width: 200px;
  height: 200px;
  background: blue;
  position: absolute;
}

@keyframes fadeOutLeft {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
    transform: translate3d(-100%, 0, 0);
  }
}

.wraper:hover .infront {
  animation: fadeOutLeft 2s;
}
<div class="wraper">
  <div class="behind"></div>
  <div class="infront"></div>
 <div>


来源:https://stackoverflow.com/questions/44344978/css-keyframe-animations-on-hover-animation-resetting-with-mouse-movement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!