CSS Keyframe animation: Hiding element before animation starts

不打扰是莪最后的温柔 提交于 2020-01-12 05:30:08

问题


Is there a CSS way to hide an element and fading it in with a keyframe-animation after x seconds? Or do I need JavaScript/jQuery for that? How to do it?

At the moment, it is also show before the animation starts and if I set opacity: 0;, the animation jumps back to that value after the animation is complete.

Fiddle


回答1:


You are close. An easy way is to just add animation-fill-mode: forwards; which will persist the last keyframe and in this case keep the div visible.

Here's an updated version of your Fiddle where the animation starts after 4s (as you specified) and keeps the div visible instead of jumping back to it's original state (opacity: 0;).

Hope that helps!




回答2:


Easiest method would just be adding this to the CSS:

 animation-fill-mode: both;

Will hold the animation before and after.




回答3:


If you want to use @keyframes, apply the delay with the use of keyframes.

You can change a delay of 4s and an animation duration of 1s into an animation of 5s with keyframes starting at 80%.

See fiddle.

@-webkit-keyframes slidein {
    0% { opacity: 0; }
    80% { opacity: 0; }
    100% { opacity: 1; }
}

@-moz-keyframes slidein {
    0% { opacity: 0; }
    80% { opacity: 0; }
    100% { opacity: 1; }
}

@-o-keyframes slidein {
    0% { opacity: 0; }
    80% { opacity: 0; }
    100% { opacity: 1; }
}

@keyframes slidein {
    0% { opacity: 0; }
    80% { opacity: 0; }
    100% { opacity: 1; }
}

div {
    position: absolute;
    width: 50px;
    height: 50px;
    top: 150px;
    right: 150px;
    background-color: black;
    -webkit-animation: slidein 5s ease 1 normal;
       -moz-animation: slidein 5s ease 1 normal;
         -o-animation: slidein 5s ease 1 normal;
            animation: slidein 5s ease 1 normal;
}



回答4:


If you want your animation to be something different than a fade-in using opacity, e.g. animate the width; you could put the opacity:1; on 1% of the animation:

@keyframes slidein {
  0% {
    opacity:0;
    width:0;
  }
  1% {
    opacity:1;
  }
  100% {
    opacity:1;
    width:100px;
  }
}

Note that you have to repeat the opacity:1; at the end of the animation, i.e. 100%. Otherwise it will fade that element out.




回答5:


You are probably looking at using CSS transitions - this page probably has the answer you are looking for.



来源:https://stackoverflow.com/questions/15404520/css-keyframe-animation-hiding-element-before-animation-starts

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