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

新手上路,请多包涵

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

这是标记:

   <div class="container">
    <div class="slide-box" id="slide-box""></div>
  </div>

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

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

原文由 Jared Garcia 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答

使用 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(); });
 .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;
  }
}
 <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>

原文由 Scott 发布,翻译遵循 CC BY-SA 3.0 许可协议

animation: slide 5s linear forwards;

在 100%

 opacity: 0;
display: none;

试试这个。

工作小提琴: https ://jsfiddle.net/jbtfdjyy/1/

更新:JS mani

 var slideBox = document.getElementById('slide-box');

setTimeout(function(){
    slideBox.style.display = 'none';
}, 5000);

试试这个。 https://jsfiddle.net/jbtfdjyy/2/

原文由 hdotluna 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题