首页 > 解决方案 > 插入新元素时如何平滑移动?

问题描述

我在其他元素的中间插入了一个新的 div 元素,我希望其他元素以流畅的方式移动到他们的新位置,而不是像现在这样突然移动。

这是我的代码:https ://codepen.io/BigEiffelTower/pen/vYBgqZq

<div id="top">
  Top of the page
</div>

<div id="middle">

</div>

<div id="bottom">
  <form> 
    <input type="button" value="Add an element">
  </form>
  End of the page
</div>
#top, #middle, #bottom {
  font-size: 1.5em;
  border: 2px solid black;
  margin: 0.3em
  transition: all 2s ease;
}
var btn = document.querySelector('input');
btn.addEventListener('click', updateBtn);

function updateBtn() {
    $el = $("<div>", {
            id: 'middle-item',
            text: "New element"
        });
    $("#middle").append($el);
}

单击按钮时如何使#three元素平滑移动?

标签: javascripthtmlcsssmoothinginsertion

解决方案


你可以用animate()函数来做到这一点。

var btn = document.querySelector("input");
btn.addEventListener("click", updateBtn);

function updateBtn() {
  $el = $("<div>", {
    id: "middle-item",
    text: "New element",
    style: "display: none"
  });
  $("#middle")
    .append($el)
    .animate({ height: "+=" + $el.height() }, 200, function() {
      $el.fadeIn(100);
    });
}
/* You don't need to define a `css transition` anymore. */
#top, #middle, #bottom {
  font-size: 1.5em;
  border: 2px solid black;
  margin: 0.3em
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="top">
  Top of the page
</div>

<div id="middle">

</div>

<div id="bottom">
  <form>
    <input type="button" value="Add an element">
  </form>
  End of the page
</div>


推荐阅读