首页 > 解决方案 > 从div中的dom中删除项目时的CSS动画/关键帧?

问题描述

我编写了一些自动执行 BS4 toast 的代码,这样我就可以使用选项即时调用它们。当一个新的 toast 添加到容器中时,它会显示在前一个下方。当 toast 过期时,它会从 dom 中删除。当这种情况发生时,toast 会淡出(由于 BS 的 .fade .show 类),当动画完成时,整个 toast 就会从 dom 中删除。一切正常,但此时也是容器中的任何其他吐司“向上/向下”的时候,因为已经移除了一个。当从 dom 中删除另一个 toast 时,有没有办法为现有 toast 的运动设置动画?所以他们不会“跳入”他们的新位置?

这是我的容器有两个吐司时我正在查看的示例:

<div id="toasts" aria-live="polite" aria-atomic="true">
    <div id="toasts-container">

        <div id="App_toast_288951045797" class="toast toast-info fade show" role="alert" aria-live="assertive" aria-atomic="true" data-autohide="false">
            ...content
        </div>

        <div id="App_toast_288951046236" class="toast toast-info fade show" role="alert" aria-live="assertive" aria-atomic="true" data-autohide="false">
            ...content
        </div>

    </div>
</div>

在 toast 关闭后从 dom 中删除:

$('body').on('hidden.bs.toast', '.toast', function () {
    $(this).remove();
});

对于那些不明白我在问什么的人。

<div id="div1">number one</div>
<div id="div2">number two</div>
<div id="div3">number three</div>

将以上内容放在一个页面中。从 dom 中删除 #div1。怎么了?#div2 和#div3 向上移动,因为#div1 不再存在。我想知道这个动作是否可以动画,所以它不会立即发生。

标签: jquerybootstrap-4css-animationskeyframe

解决方案


您的问题中没有足够的(非伪)HTML,我无法为您提供更有用的代码段,但下面是一个简单的示例,应该可以理解这一点。

解决方案是为元素的高度设置动画。

基本方法:

  1. 淡出元素
  2. 一旦它淡出,动画/过渡它的高度到 0px
  3. 在它的高度为零像素后,将其从 DOM 中删除

尝试单击此处列表中的第一项或第二项:

$(function() {
  $('.toast').on('click', function() {
    var $this = $(this);
    $this.addClass('animate');
    setTimeout(function() {
      $this.remove();
    }, 800);
  });
});
.toast {
  height: 30px;
  opacity: 1;
  transition: opacity 350ms ease, height 350ms ease 400ms;
  color: white;
  cursor: pointer;
}
.toast:nth-child(1) {
  background-color: navy;
}
.toast:nth-child(2) {
  background-color: steelblue;
}
.toast:nth-child(3) {
  background-color: powderblue;
}
.animate {
  opacity: 0;
  height: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="toasts">
  <div class="toast">lorem ipsum</div>
  <div class="toast">dolor sit amet</div>
  <div class="toast">consectetur adipiscing</div>
</div>


推荐阅读