问题
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