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

标签 html css animation dom

我有一个 div 滑出 View 的动画,但是当动画完成时,div 只是返回到它在 View 中的原始位置。如何在动画结束后仅使用 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% 时消失。提前致谢!

最佳答案

使用 animation-fill-mode 选项。将其设置为 forwards,动画将在其最终状态结束并保持这种状态。

根据评论更改 将不透明度淡入淡出设置为仅最后 1% 的动画...简化关键帧。添加了一个 jquery 选项以从字面上从 DOM 中删除 div。 CSS 本身不会改变标记,而 jQuery 会。

尽管您不能为 display 属性设置动画。如果您希望 div 完全消失,在不透明度逐渐变为零后,您可以添加显示属性以删除 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>

关于html - 使用 CSS 动画完成后从 DOM 中删除/隐藏 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39198083/

相关文章:

PHP addChild 到列表顶部?

jquery - 呈现 HTML 页面预览

html - 填充导航栏元素会影响所有导航栏

html - 使用 CSS 设置背景图像而不放大

css - Bootstrap 表单行宽

c++ - QPropertyAnimation 中支持哪些属性被动画化?

python - 无法使用 ffmpeg 保存 Matplotlib 动画

html - margin :auto not working in ie5

javascript - 在按钮下

android - 在开始新 Activity 之前允许动画完成