我有一个像
这样的字符串content = "content1<br/>content2<br/>"
我将content3
添加到字符串中,结果就像
content1
content2
content3
我希望展示新内容的content
容器具有动画高度。
我试过了
document.getElementById("detail").innerHTML = content;
$("detail").animate({
height: 'auto'
}, 1000);
它只是在没有动画的情况下出现
答案 0 :(得分:2)
制作未知高度的动画很棘手。我会尝试使用CSS转换和javascript辅助函数的组合来计算新的宽度。
当然你仍然只能使用animate
,但你仍然需要计算新的身高和动画到新的高度。
var content = "content1<br/>content2<br/>";
var height = getHeight(content);
$("#detail").css('max-height', height).html(content);
setTimeout(function() {
content += 'content3<br/>';
var height = getHeight(content);
$("#detail").css('max-height', height).html(content);
}, 1000);
function getHeight(str) {
var $tmp = $("<div>").html(content).css({position: 'absolute', top: -1000}).appendTo('body'),
height = $tmp.height() + 10 + 'px';
$tmp.remove();
return height;
}
&#13;
#detail {
background: #EEE;
overflow: hidden;
max-height: 0;
transition: max-height 1s ease;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="detail"></div>
&#13;
答案 1 :(得分:0)
这是因为jQuery .Animate()仅适用于数字。
例如,您当前的高度为:20px
,并且您在动画函数中将其设为30px
。
jQuery将在声明的时间内上升20到30,并将其连续设置为元素,直到达到30。
另一方面,CSS比JS更快地运行,并使元素自动自动加重。所以你必须使用数字来设置新高度的动画(前一个高度也必须是一个数字)或者你可以使用CSS3过渡。
FIDDLE此处