由于内容更改,如何更改宽度/高度的动画?

时间:2016-09-22 22:28:24

标签: css3 animation css-transitions css-animations

在下面的示例中,单击该按钮时,会将一些内容添加到div中。我想动画div越来越大。这可以用纯CSS吗?

$('#btn').on('click', function() {
  $('#content').append("<p>Ab atque aut cumque dolor exercitationem officia, perferendis quis vel. Autem deserunt ea maiores quaerat quos temporibus! Aperiam dolorem dolores, eaque ex ipsam laborum minima nesciunt nulla porro quaerat vel?</p>");
});
#content {
  background-color: yellow;
  
  transition: width 1s, height 1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">

  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab cupiditate debitis dolores dolorum ea, eligendi ex, expedita illum incidunt ipsum itaque neque optio quisquam quo vel veniam voluptatem voluptatibus, voluptatum.</p>

</div>

<button id="btn">click me</button>

1 个答案:

答案 0 :(得分:3)

您需要对#content使用掩码包装并将css过渡应用于它并使用Javascript更改它的高度。每次附加新内容(高度变化)时,您都需要从#content中获取新的高度。

var $contentMask = $('#contentMask');
var contentBoxId = '#content';
var currentHeight = getCurrentHeight(contentBoxId);
$contentMask.css('height', currentHeight);

$('#btn').on('click', function() {
  $(contentBoxId).append("<p>Ab atque aut cumque dolor exercitationem officia, perferendis quis vel. Autem deserunt ea maiores quaerat quos temporibus! Aperiam dolorem dolores, eaque ex ipsam laborum minima nesciunt nulla porro quaerat vel?</p>");
  currentHeight = getCurrentHeight(contentBoxId);
  $contentMask.css('height', currentHeight);
});

function getCurrentHeight(selector) {
 return $(selector).height();
}
#content {
  background-color: yellow;
}
#contentMask {
  overflow: hidden;
  transition: height 1s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="contentMask">
  <div id="content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab cupiditate debitis dolores dolorum ea, eligendi ex, expedita illum incidunt ipsum itaque neque optio quisquam quo vel veniam voluptatem voluptatibus, voluptatum.</p>
  </div>
</div>

<button id="btn">click me</button>

你也可以在jsfiddle中看到它:https://jsfiddle.net/iamgutz/fsagbLn9/