Jquery 获取所有子项的高度并将其应用于父项
我试图计算一个Jquery 获取所有子项的高度并将其应用于父项,jquery,html,css,Jquery,Html,Css,我试图计算一个“height:auto”div的高度,然后将其应用于div。我是这样做的: function center(divName) { $(":animated").promise().done(function () { var totalHeight = 0; $(divName).children().each(function () { alert(totalHeight); totalH
“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>
使用背景色:红色设置高度后:
我通过将
.height()
更改为.outerHeight(true)
代码:
我可能遗漏了一些明显的东西,但这不是因为
alert(totalHeight)
需要在totalHeight+=$(this).height()之后代码>?如何设置动画?通过css3
或jQuery的.animate()
在计算totalheight之前发出警报,因此对于第一个子项,其显示为0。像这样试试,totalHeight+=$(this.height();警报(总高度);那么,您的代码返回68px
-是否不正确?你可能也想得到marging
s?马特:加起来的高度仍然是错误的,我想得到的是中间一个div,但要做到这一点,我需要设置一个高度。Jai:我正在使用.animate()。更新我的问题以便更好地解释
#frame_01 {
text-align: center;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
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");