jquery - 获取所有 child 的高度并将其应用于 parent

标签 jquery html css

我正在尝试计算 "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设置高度后:

enter image description here

最佳答案

我通过将 .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/

相关文章:

javascript - 检查是否输入了正确的电子邮件

javascript - 单击附加的外部内容不起作用

HTML - 显示图像/图标/用户界面元素的语义方式?

html - 标题移动其他菜单项并将它们的文本对齐到其底部

css - 移动菜单始终打开

jquery - 在 Bootstrap 3 中将切换按钮居中

jQuery radio onchange 切换父元素的类?

javascript - 当光标位于 iFrame 上时,鼠标滚轮不起作用

javascript - 如何从 reactJS 中的文件中获取字节数组

javascript - 为什么我的网站中的脚本会出现此错误?