Animate Div Height on AppendChild

时间:2015-07-28 17:15:17

标签: javascript css

How can I add a smooth transition to the change in height when a new paragraph is appended inside a div? Example: https://jsbin.com/wahasikaki/edit?html,css,js,output

I know this may be possible with jQuery, but is it possible to do it using pure CSS?

1 个答案:

答案 0 :(得分:2)

它不是纯CSS,但是你已经用javascript添加你的段落了。 问题是,为了在CSS中设置动画高度,您需要使用值。您将需要javascript来提取这些高度值。 您可以做的是在添加段落之前使用scrollHeight测量面板的高度,然后在添加段落之后测量下一步。 然后,您可以更改面板CSS的高度。

使用额外的div inner-panel,其位置相对于包装段落。这个div必须具有相对的位置属性。

我还添加了一些CSS

溢出:隐藏;



function addParagraph() {

  document.getElementById("panel").style.height = document.getElementById("inner-panel").scrollHeight + "px";

  var newParagraph = document.createElement("p");

  newParagraph.innerHTML = "League salmagundi Jack Tar wherry scuppers Gold Road bring a spring upon her cable grog blossom lanyard Yellow League salmagundi Jack Tar wherry scuppers Gold Road bring a spring upon her cable grog blossom lanyard Yellow ";

  document.getElementById("inner-panel").appendChild(newParagraph);

  console.log(document.getElementById("panel").scrollHeight);

  document.getElementById("panel").style.height = document.getElementById("inner-panel").scrollHeight + "px";
}

function removeParagraph() {

  var popParagraph = document.getElementById("inner-panel").lastChild;

  popParagraph.parentNode.removeChild(popParagraph);

  document.getElementById("panel").style.height = document.getElementById("inner-panel").scrollHeight + "px";
}

#panel {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #000;
  color: #fff;
  font-family: Arial, sans-serif;
  font-size: 0.875em;
  transition: all 1s;
  max-height: 95%;
  overflow: hidden;
}
#inner-panel {
  position: relative;
  padding: 0 1em;
  overflow: hidden;
}
p {
  background: #333;
  padding: 1em;
  line-height: 150%;
  border-radius: 4px;
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body>
  <button onclick="addParagraph();">Add Paragraph</button>
  <button onclick="removeParagraph();">Remove Paragraph</button>
  <div id="panel">
    <div id="inner-panel">
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
        It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
        desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    </div>
  </div>
</body>

</html>
&#13;
&#13;
&#13;