I need to have two animations in css, one at start and one at hover, but it isn't working

拜拜、爱过 提交于 2019-12-24 02:55:12

问题


I have a div element, which has an animation to play when starting the page. I want to make it have another animation to play when I'm hovering over it. It works just fine, but when I get my mouse out of the div element, it plays the starting animation again (fades in from out of the screen).

@keyframes div{
   0%{
     opacity: 0;
   }
}
@keyframes divHover{
   50%{
      top: 200px;
   }
   100%{
      top: 0px;
   }
}
#div{
   opacity: 1;
   animation: div 1s;
   position: absolute;
   left: 0px;
   top: 0px;
}
#div:hover{
   animation: divHover 1s linear 0s infinite;
}
   <div id="div"> abc </div>

Expected: Div starts invisible and fades in. When hovering div, it goes up and down, and keeps doing it while hovering. After stopping the hover, div stops the animation and keeps its full opacity

Actual: After stopping the hover, div stops the animation but returns to 0 opacity, then takes one second to display the starting animation again.

https://jsfiddle.net/odq125Lu/6/


回答1:


The issue is due to the fact that you are overriding the first opacity animation with the up & down one then when you unhover you active the first one again.

You can use multiple animations and consider animation-play-state to activate the second one:

@keyframes div {
  0% {
    opacity: 0;
  }
}

@keyframes divHover {
  50% {
    top: 200px;
  }
  100% {
    top: 0px;
  }
}

#div {
  opacity: 1;
  animation: 
    div 1s,
    divHover 1s linear 0s infinite;
  animation-play-state:running,paused;
  position: absolute;
  left: 0px;
  top: 0px;
  background:red;
  padding:20px;
}

#div:hover {
  animation-play-state:running,running;
}
<div id="div"> abc </div>



回答2:


I'm no expert, but it may have something to do with the fact that you haven't set a 100% value for the animation "divHover"?

@keyframes div{
   0%{
     opacity: 0;
   }
   100% {
     opacity: 1;
   }
}


来源:https://stackoverflow.com/questions/56508813/i-need-to-have-two-animations-in-css-one-at-start-and-one-at-hover-but-it-isn

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