innerHTML更改时的动画高度调整

Pie*_*ter 5 html javascript jquery

我有这个主意...假设我有一个包含一些文本的DIV。

<div id="myDIV">Testing testing lorem ipsum</div>
Run Code Online (Sandbox Code Playgroud)

如果我通过执行以下操作来更改此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")
Run Code Online (Sandbox Code Playgroud)

DIV的高度将改变。

是否可以对此突然的高度变化进行动画处理以平滑过渡?

Bri*_*gan 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);
Run Code Online (Sandbox Code Playgroud)