动画完成后使用CSS删除/隐藏DOM中的div?

Jar*_*cia 5 html css animation dom

我有一个动画,其中div滑出视图,但是当动画完成时,div只返回到视图中的原点位置.如何在动画结束后使用CSS完全删除div或隐藏它?

这是标记:

  <div class="container">
    <div class="slide-box" id="slide-box""></div>
  </div>
Run Code Online (Sandbox Code Playgroud)

和css:

.slide-box {
  position: relative;
  width: 100px;
  height: 100px;
  background-image: url(../pics/red.png);
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;

  animation: slide 5s linear 1;
}
@keyframes slide {
  0% {
    left: 0;
  }
  20% {
    left: 20%;
  }
  40% {
    left: 40%;

  }
  60% {
    left: 60%;

  }
  80% {
    left: 80%;
  }
  100% {
    left: 100%;
    overflow: hidden;
    visibility: hidden;
  }
}
Run Code Online (Sandbox Code Playgroud)

我不希望它在动画的持续时间内淡出,我只是希望它在关键帧中达到100%时消失.提前谢谢!

Sco*_*ott 8

使用该animation-fill-mode选项.设置为forwards,动画结束于它的最终状态并保持这样.

根据注释进行更改设置不透明度淡化为动画的最后1%...简化的关键帧.添加了一个jquery选项,从字面上删除DOM中的div.单独使用CSS不会改变jQuery的标记.

虽然您无法为该display属性设置动画.如果你想让div完全消失,在不透明度渐渐变为零之后,你可以添加display属性来删除div.如果你等待不透明度结束,div就会消失而没有任何过渡.

/* 

This jquery is added to really remove 
the div. But it'll essentially be 
VISUALLY gone at the end of the 
animation. You can not use, or 
delete the jquery, and you really 
won't see any difference unless 
you inspect the DOM after the animation.

This function is bound to animation 
and will fire when animation ends. 
No need to "guess" at timeout settings. 
This REMOVES the div opposed to merely 
setting it's style to display: none;  

*/

$('.slide-box').bind('animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd', function(e) { $(this).remove(); });
Run Code Online (Sandbox Code Playgroud)
.slide-box {
  display: block;
  position: relative;
   left: 0%;
  opacity: 1;
  width: 100px;
  height: 100px;
  background: #a00;
  animation: slide 1s 1 linear forwards;
  
  /*
	animation-name: slide;
	animation-duration: 1s;
	animation-iteration-count: 1;
	animation-timing-function: linear;
	animation-fill-mode: forwards;
 */
}

@keyframes slide {
  0% {
   left: 0%;
  opacity: 1;
  }
  99% {
    left: 99%;
    opacity: 1;
  }
  100% {
    left: 100%;
    opacity: 0;
    display: none;
  }
}

@-webkit-keyframes slide {
  0% {
    left: 0%;
  opacity: 1;
  }
  99% {
    left: 99%;
    opacity: 1;
  }
  100% {
    left: 100%;
    opacity: 0;
    display: none;
  }
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="slide-box" id="slide-box"></div>
  </div>
Run Code Online (Sandbox Code Playgroud)