应用后如何反转关键帧

How to reverse the keyframe once it's applied

这里是我使用的动画和javascript代码在点击特定按钮时添加相应的类。它工作正常。

$(document).ready(() => {

 $('.show').on('click', () => {
   $('.child').addClass('show');
  })
  
  $('.hide').on('click', () => {
   $('.child').addClass('hide');
  })
  
})
.child{
  width:0;
  height:0;
  border:2px solid red;
  overflow:hidden;
}

.child.show{
   animation-name: expandit;
   animation-duration: 1s;
   width:100px;
   height:100px;
}

.child.hide{
   animation-name: hideit;
   animation-duration: 1s;
   animation-direction: reverse;
}


@keyframes expandit {
  0% {
    width: 0;
  }
  100% {
    width: 100px;
  }
}

@keyframes hideit {
  0% {
    width: 0;
  }
  100% {
    width: 100px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <a class="show" href="#">Show</a>
  <a class="hide" href="#">Hide</a>
  <div class="child">
    
  </div>
</div>

现在用户点击关闭按钮。我想通过使用关键帧将宽度恢复为 0。我该怎么做?

谁能帮帮我?

您正在寻找 animation-fill-mode 属性,它允许您将动画的最终状态应用为 documented on w3c

$(document).ready(() => {

  $('.show').on('click', () => {
    $('.child').addClass('show');
  })

  $('.hide').on('click', () => {
    $('.child').addClass('hide');
  })

})
.child {
  width: 0;
  height: 0;
  border: 2px solid red;
  overflow: hidden;
}

.child.show {
  animation-name: expandit;
  animation-duration: 1s;
  width: 100px;
  height: 100px;
}

.child.hide {
  animation-name: hideit;
  animation-duration: 1s;
  animation-direction: reverse;
  animation-fill-mode: forwards;
}

@keyframes expandit {
  0% {
    width: 0;
  }
  100% {
    width: 100px;
  }
}

@keyframes hideit {
  0% {
    width: 0;
  }
  100% {
    width: 100px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <a class="show" href="#">Show</a>
  <a class="hide" href="#">Hide</a>
  <div class="child">

  </div>
</div>

但是,如果您想恢复到 height: 0; 的 "real initial state",则需要在 99.99% 处添加一个额外的关键帧来隐藏第二个动画。如果您有任何后续问题,请随时发表评论。