插入新元素时如何平滑移动?

How to have smooth movements when inserting a new element?

我在其他元素中间插入一个新的 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元素平滑移动?

希望这段代码对您有所帮助:

HTML:

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

<div id="middle">
  <ul>
  </ul>

</div>

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

CSS:

button {
  display: block;
  margin: 0 auto;
  cursor: pointer;
  border: none;
  width: 150px;
  height: 40px;
  border-radius: 5px;
}

ul {
  list-style: none;
  padding: 10px;
  margin: 0;
  text-align: center;
}

li {
  width: 100px;
  height: 50px;
  cursor: pointer;
  margin: 0 3px;
  transform-orgin: center;
  transition: all 0.2s ease-in-out;
  animation-name: popin;
    animation-duration: 0.3s;
    animation-timing-function: easeout;
}

li.transReset {
  transition: intial;
}

li:hover{
  transform: scale(1.2);
}


@keyframes popin {
  0% {
    transform: scale(0.2);
  }
  75% {
    transform: scale(1.2);
    animation-timing-function: easeout;
  }
  100% {
    transform: scale(1);
  }
}

JAVASCRIPT:

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

function updateBtn() {
    $el = $("<li>", {
            id: 'middle-item',
            text: "New element"
        });
    $n = $("<li></li>").hide().addClass('transReset');
    $("#middle").append($el);
     $n.show(300, function() {  $(this).removeClass('transReset') });
}

您可以使用 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>