Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 获取所有子项的高度并将其应用于父项_Jquery_Html_Css - Fatal编程技术网

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");