CSS animation keyframes with display none works to fade in, but not fade out

后端 未结 2 2032
萌比男神i
萌比男神i 2021-01-22 01:26

I have an element which has display none on start. When i add a class to it i want it to fade in, using CSS.

I found this tutorial to use keyframes which is working nice

2条回答
  •  面向向阳花
    2021-01-22 01:51

    You can't animate or transition the display property.

    Note: That's not to say you can't use it in keyframe animation but that's not the same as actually animating it.

    The reason why your Codepen demo doesn't work as intended is because the .active class is being removed instantly so the animation out has no time to fire and the default display:none is now applied immediately.

    Since you are using Jquery anyway, there is a built in function fadeToggle which will do what you want.

    $('button').on('click', function(e) {
      e.preventDefault();
      $(this).siblings('.box').fadeToggle(500);
    })
    * {
      box-sizing: border-box;
      text-align: center;
    }
    button {
      margin: 30px 0;
      border: 1px solid #ccc;
      text-align: center;
      padding: 1em;
      background: none;
      box-shadow: none;
    }
    .box {
      margin: 0 auto;
      width: 80%;
      display: none;
      line-height: 100px;
      background: #ccc;
      border: 1px solid #444;
      text-align: center;
    }
    
    

    I move nicely!

提交回复
热议问题