简体   繁体   English

CSS动画-淡入和淡出

[英]CSS animations - fading in and fading out

I'm trying to do some animations on a menu in CSS. 我正在尝试在CSS菜单上制作一些动画。 Below is the code I have to get the menu to fade in when I hover over the heading. 以下是我将鼠标悬停在标题上时必须使菜单淡入的代码。 I've also added similar CSS rules for fading out but I can't get it to work the way I want. 我还添加了用于淡出的类似CSS规则,但无法使其按我想要的方式工作。

Tried a few things but the best I could do was getting it to fade in and then as soon as it is at full opacity it fades out again till the end of the animation and then just displays the block, so it basically fades ina and then out before just appearing as if there was no animation. 尝试了几件事,但是我能做的最好的事情是让它淡入淡出,然后在完全不透明时,它再次淡出直到动画结束,然后只显示该块,所以基本上从ina淡出,然后出来之前,好像没有动画。

 ul{ list-style:none; padding:0px; margin:0px; } ul >li >ul{ display:none; } ul >li:hover >ul{ display:block; } .fade_in { -webkit-animation-name: fade_in; -webkit-animation-duration: 1s; animation-name: fade_in; animation-duration: 1s; } @-webkit-keyframes fade_in { from {opacity: 0} to {opacity: 1} } @keyframes fade_in { from {opacity: 0} to {opacity: 1} } .fade_out { -webkit-animation-name: fade_in; -webkit-animation-duration: 1s; animation-name: fade_in; animation-duration: 1s; } @-webkit-keyframes fade_out { from {opacity: 1} to {opacity: 0} } @keyframes fade_out { from {opacity: 1} to {opacity: 0} } 
 <ul> <li>Heading <ul class="fade_in"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </li> </ul> 

What you want to achieve is by far easier using a CSS transition instead of an animation , like so: 到目前为止,要实现的目标是使用CSS 过渡而不是动画来实现,例如:

transition: opacity .4s ease-in-out;

Because you can neither animate nor transition the display property, I've changed the default state from display: none; 因为您既不能设置动画也不能转换display属性,所以我将display的默认状态更改为display: none; to opacity: 0; opacity: 0; .

 ul { list-style: none; padding: 0; margin: 0; } ul>li>ul { opacity: 0; position: absolute; pointer-events: none; transition: opacity .4s ease-in-out; } ul>li:hover>ul { pointer-events: all; opacity: 1; } 
 <ul> <li>Heading <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </li> </ul> 

you could try something like this 你可以尝试这样的事情

HTML HTML

<div>Heading
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
</div>

CSS CSS

ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

div>ul {
    opacity: 0;
    position: absolute;
    pointer-events: none;
    visibility: hidden;
    transition: visibility 0s 1s, opacity 1s linear;
    overflow: hidden;
}

div:hover>ul {
    pointer-events: all;
    visibility: visible;
    opacity: 1;
    transition: opacity 1s linear;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM