innerHTML更改时的动画高度调整

时间:2010-09-17 17:07:53

标签: javascript jquery html

我有这个想法...让我说我有一个包含一些文字的DIV。

<div id="myDIV">Testing testing lorem ipsum</div>

如果我通过执行类似

的操作来更改此DIV的内容
$("div#myDIV").html("New text New text New text New text New text New " +
  "text New text New text New text New text New text New text New text " +
  "New text New text New text New text")

DIV的高度会改变。

是否有可能为突然的高度变化设置动画以平滑过渡?

1 个答案:

答案 0 :(得分:1)

它不漂亮,但这可能是一个解决方案。我们的想法是用另一个充当掩码的div包装你的内容div。这样,内部div的高度可以在更新后计算,并且动画可以应用于蒙版:

// Get current height of container div.
var containerHeight = $('#container').outerHeight();

// Manually set height of container div.
$('#container').css({height: containerHeight});

// Update the html of the content div.
$('#container div').html('New text New text New text New text New text New ' +
     'text New text New text New text New text New text New text New text ' +
     'New text New text New text New text');

// Get the height of the content div.
var contentHeight = $('#container div').outerHeight();

// Animate the height of the container div to the content height.
$('#container').animate({height:contentHeight}, 1000);