CSS动画-淡入和淡出

时间:2018-09-06 14:35:19

标签: html css css-animations

我正在尝试在CSS菜单上制作一些动画。以下是我将鼠标悬停在标题上时必须使菜单淡入的代码。我还添加了类似的CSS规则以进行淡化,但是我无法使其按我想要的方式工作。

尝试了几件事,但是我能做的最好的事情就是让它淡入,然后在它完全不透明时再次淡出直到动画结束,然后只显示该块,所以基本上就淡了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>

2 个答案:

答案 0 :(得分:2)

到目前为止,要使用CSS 过渡(而不是 animation )来实现您想要的目标,就像这样:

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

由于您既不能设置动画也不能过渡display属性,因此我将默认状态从display: none;更改为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>

答案 1 :(得分:0)

您可以尝试这样的事情

HTML

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

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;
}