我想要动画的高度从200px
到auto
<div>
。不过,我似乎不能让它工作。有人知道是怎么回事吗?
代码如下:
$("div:first").click(function(){
$("#first").animate({
height: "auto"
}, 1000 );
});
发布于 2014-07-15 23:57:40
IMO这是最干净、最简单的解决方案:
$("#first").animate({height: $("#first").get(0).scrollHeight}, 1000 );
说明: DOM已经从它的初始渲染中知道,当设置为自动高度时,展开的div将有多大。此属性作为scrollHeight
存储在DOM节点中。我们只需通过调用get(0)
从jQuery元素获取DOM元素,然后就可以访问该属性了。
添加回调函数以将高度设置为auto后,可以在动画完成后获得更高的响应性(信用chris-williams):
$('#first').animate({
height: $('#first').get(0).scrollHeight
}, 1000, function(){
$(this).height('auto');
});
发布于 2012-03-13 00:31:55
更好的解决方案不是依赖JS来设置元素的高度。以下是将固定高度元素设置为全(自动)高度动画的解决方案:
var $selector = $('div');
$selector
.data('oHeight',$selector.height())
.css('height','auto')
.data('nHeight',$selector.height())
.height($selector.data('oHeight'))
.animate({height: $selector.data('nHeight')},400);
发布于 2012-10-05 19:24:19
这是有效的,而且比以前的解决方案更简单:
CSS:
#container{
height:143px;
}
.max{
height: auto;
min-height: 143px;
}
JS:
$(document).ready(function() {
$("#container").click(function() {
if($(this).hasClass("max")) {
$(this).removeClass("max");
} else {
$(this).addClass("max");
}
})
});
注意:此解决方案需要jQuery UI
https://stackoverflow.com/questions/5003220
复制相似问题