从div中的dom中删除项目时的CSS动画/关键帧?

问题描述 投票:0回答:1

我写了一些自动化BS4吐司的代码,所以我可以随意调用它们。当一个新的吐司被添加到容器中时,它显示在前面的下方。当吐司过期时,它将从dom中删除。当发生这种情况时,toast会淡出(由于BS的.fade .show类),当动画完成时,整个toast将从dom中删除。一切都按预期工作,但此时也是任何其他任务在容器中“上升/下降”的时候,因为一个已被移除。当从dom中移除另一个吐司时,有没有办法动画现有吐司的运动?所以他们不会“跳”到新的位置?

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

<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>

吐司关闭后从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不再存在。我想知道这个动作是否可以动画,所以它不会立即发生。

jquery bootstrap-4 css-animations keyframe
1个回答
1
投票

你的问题中没有足够的(非伪)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>
© www.soinside.com 2019 - 2024. All rights reserved.