【问题标题】:Animated height adjustment when innerHTML changesinnerHTML 更改时的动画高度调整
【发布时间】:2010-09-18 03:00:00
【问题描述】:

我有这个想法...假设我有一个包含一些文本的 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 的高度会改变。

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

【问题讨论】:

  • 你的意思是jsbin.com/ikaji4 ??
  • 是的,但我不希望 DIV 完全上下滑动。我只想要一个到新高度的动画过渡。

标签: javascript jquery html


【解决方案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);

【讨论】:

  • 我在这里尝试过:jsfiddle.net/zSUfa/2 我预计在执行$('#container').css({height: containerHeight}); 后会下推“其他内容”(这将是不受欢迎的行为),但那没有发生。为什么放大的容器没有像我预期的那样过早地将“其他内容”向下推?
  • 在此脚本中,您正在为容器节点的高度设置动画。它将在动画期间“推”下“段落”节点(默认情况下是块元素 - 就像 div 的一样)。您所看到的只是浏览器在做它应该做的事情。
  • 哦,我现在明白了......我读错了你的代码。但它有效,所以谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-01
  • 2015-01-02
  • 2021-02-01
  • 2013-09-11
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多