【问题标题】:CSS animation/keyframes when items are removed from dom in div?从div中的dom中删除项目时的CSS动画/关键帧?
【发布时间】:2019-05-02 07:19:24
【问题描述】:

我编写了一些自动执行 BS4 toasts 的代码,这样我就可以通过选项即时调用它们。当一个新的 toast 添加到容器中时,它会显示在前一个下方。当 toast 过期时,它会从 dom 中删除。当这种情况发生时,toast 会淡出(由于 BS 的 .fade .show 类),当动画完成时,整个 toast 就会从 dom 中删除。一切都按应有的方式工作,但此时也是容器中的任何其他吐司“向上/向下”的时候,因为已经移除了一个。当从 dom 中删除另一个 toast 时,有没有办法为现有 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 不再存在。我想知道这个动作是否可以动画化,这样它就不会立即发生。

【问题讨论】:

  • 不清楚我在问什么——真的吗?

标签: jquery bootstrap-4 css-animations keyframe


【解决方案1】:

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

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

基本方法:

  1. 淡出元素
  2. 一旦淡出,将其高度设置为动画/过渡到 0 像素
  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>

【讨论】:

  • 好的,当我在 .toast 上使用设定高度时,我得到了这个结果,并且具有我正在寻找的行为,但我不能为其设定高度 - 需要是动态的.附近有什么工作吗?
  • @user756659 因为您不能仅使用 CSS 从 auto 转换到其他东西,所以最好的办法是在设置动画之前立即获取计算高度,将其设置为内联高度,然后做动画。查看element.getBoundingClientRect()。如果您在项目之间有边距,则您还需要考虑这些边距,以实现最佳过渡。这有点复杂。
  • 感谢您为我指明正确的方向。是的,我已经意识到我需要border-width:0;和边距底部:0;在我的动画课上也是如此,以确保一切顺利。
猜你喜欢
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
  • 2013-04-20
  • 2021-12-08
  • 1970-01-01
相关资源
最近更新 更多