我正在尝试计算 "height: auto"
div 的高度,然后将其应用于 div。我是这样做的:
function center(divName) {
$(":animated").promise().done(function () {
var totalHeight = 0;
$(divName).children().each(function () {
alert(totalHeight);
totalHeight += $(this).height();
});
$(divName).css("height", totalHeight + "px");
});
}
center("#frame_01");
HTML:
<div id="frame_01">
<h1>Text</h1>
<h2 id="next_frame_02">Continue</h2>
</div>
注意 alert(totalHeight);
,我用它来测试脚本,问题是,脚本返回第一个子元素为 0px,但第二个子元素正确。
我首先想到这是因为它在动画完成之前开始计算,因此没有得到第一个 child 的高度,所以我应用了 $(":animated").promise().done(function( ) {
所以脚本在计算之前等待动画完成。
但这并没有解决问题,有什么建议吗?
提前致谢!
编辑:
我想要实现的是将一个 div 居中,但为此我需要 div 的高度。这是 CSS:
#frame_01 {
text-align: center;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
用background-color: red
设置高度后:
最佳答案
我通过将 .height()
更改为 .outerHeight(true)
解决了这个问题
代码:
function center(divName) {
$(":animated").promise().done(function () {
var totalHeight = 0;
$(divName).children().each(function () {
alert(totalHeight);
totalHeight += $(this).outerHeight(true);
});
$(divName).css("height", totalHeight + "px");
});
}
center("#frame_01");
关于jquery - 获取所有 child 的高度并将其应用于 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21853927/