首页 > 解决方案 > 应用后如何反转关键帧

问题描述

这是我正在使用的动画和单击特定按钮时添加相应类的 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通过使用关键帧恢复宽度。我怎样才能做到这一点?

谁能帮我?

标签: csscss-animationscss-transitions

解决方案


您正在寻找animation-fill-mode允许您保持应用动画的最终状态的属性,如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>

但是,如果您想恢复到“真正的初始状态” where height: 0;,则需要一个 99.99% 的附加关键帧来隐藏第二个动画。如果您有任何后续问题,请随时发表评论。


推荐阅读