使用javascript调整内容大小时自动高度更改的动画

时间:2012-11-11 00:37:13

标签: javascript jquery html html5 css3

当我添加更改内容长度的内容时,我想控制容器的自动高度更改。现在,如果我对内容应用innerHTML更改,则相应地更改高度。我想对这个高度变化应用过渡。我怎样才能做到这一点? (我也可以使用jQuery)

3 个答案:

答案 0 :(得分:11)

在更改内容之前记录高度,更改内容,记录高度,将高度设置为前一个高度,并设置为后一个高度的动画。动画完成后,再次将高度设置为自动。您可以使用heightanimate执行此操作。

JSFiddle上的

Try it

答案 1 :(得分:0)

<div id="containter" style="overflow:hidden">
<div>
 Content.....
</div>
</div>

//add something...
$('#container').animate({height:$('#container').content().outerHeight()});

或:

 $('#container').animate({height:$('#container').children().first().outerHeight()});

当添加附加到containter内的div时:

$('#container').children().first().append(somethingNew);

答案 2 :(得分:0)

基于icktoofay's answer

我在更改高度时禁用了按钮,并添加了褪色效果。此解决方案对于更新产品过滤器等很有用。

我还要检查box-sizing属性。如果它是box-sizing,那么在新内容具有相同高度时,我将得到.outerHeigth()而不是.height()newHeight来防止高度波动。您可以检查这种情况,例如通过将random变量设置为值5。原因是

  

.height()将始终返回内容高度,无论CSS box-sizing属性的值如何。

CodePen

$('#button').click(function() {
  var $button = $(this),
      buttonOriginalText = $button.html();
  $button.prop('disabled', true).html('Updating...');
  $('#content').animate({
    opacity: 0
  }, 'fast', function() {
    var newHeight,
        $content = $(this),
        oldHeight = $content.height();
    $content.html(getRandomContent());
    newHeight = ('border-box' === $content.css('box-sizing') ? $content.outerHeight() : $content.height());
    $content.height(oldHeight).animate({
      height: newHeight,
      opacity: 1
    }, 'slow', function() {
      $content.height('auto');
      $button.prop('disabled', false).html(buttonOriginalText);
    });
  });
});

function getRandomContent() {
  var random = 1 + Math.round(Math.random() * 11), // 1..12
      paragraph = '<p>Paragraph</p>';
  return paragraph.repeat(random);
}
* {
  box-sizing: border-box;  /* comment out to test "content-box" */
  font: 16px Helvetica, 'sans-serif';
}

.content {
  counter-reset: content;
  padding: 6px 18px;
}

.content p {
  counter-increment: content;
}

.content p:after {
  content: ' ' counter(content) '.';
}

.content-box {
  border: 2px solid red;
  margin-top: 24px;
  max-width: 220px;
}
<button id="button" class="button">Update the content</button>
<div class="content-box">
  <div id="content" class="content">Animatie the automatic height when content is resized.</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

相关问题