DIV填充剩余高度计算

And*_*Hin 1 javascript css jquery

我有以下内容:

<div id="modal-container">
  <div id="modal-body"></div>
  <div id="modal-footer"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

我正在编写一块JS来调整#modal-body以填充剩余的可用空间.这实际上比看起来更多的工作:

$('#modal-body').css({
  'height': function() {
    // the amount of vertical space we have to work with.
    // this is the height of the container (modalView)
    var containerHeight = $('#modal-container').height();

    // the amount of vertical space the footer takes up
    var footerOuterHeight = $('#modal-footer').outerHeight();

    // we have to also account for the vertical padding of our div
    var paddingTop = $(this).css('padding-top').replace('px', '');
    var paddingBottom = $(this).css('padding-bottom').replace('px', '');
    var marginTop = $(this).css('margin-top').replace('px', '');
    var marginBottom = $(this).css('margin-bottom').replace('px', '');
    var borderTop = $(this).css('border-top-width').replace('px', '');
    var borderBottom = $(this).css('border-bottom-width').replace('px', '');

    return containerHeight-footerOuterHeight-paddingTop-paddingBottom-marginTop-marginBottom-borderTop-borderBottom;
  }
});
Run Code Online (Sandbox Code Playgroud)

问题源于我们无法为#modal-body设置"outerHeight"属性,因此我们必须通过考虑它自己的填充,边框,边距等来计算它.

无论如何,上面的功能大多有效.我的两个问题是:

  1. 有没有更好/更简单的方法来做到这一点?
  2. 它似乎是1px关闭.#modal-container因此有一个滚动条,如果我减去额外的1px,它就可以了.我错过了什么?除了边距,填充和边框之外,我还有什么需要考虑的吗?

Chr*_*ris 6

有没有更好/更简单的方法来做到这一点?

就在这里.

问题源于我们无法为#modal-body设置"outerHeight"属性,因此我们必须通过考虑它自己的填充,边框,边距等来计算它.

这不一定,最终是真的.您可以使用box-sizing: border-box;,这将强制调整大小包括边框和填充,但不包括边距.所以你仍然需要处理保证金,但这将为你节省一些工作;

#yourElement {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
Run Code Online (Sandbox Code Playgroud)

编辑:您可以使用纯CSS执行此操作; 不需要JavaScript.看这个演示.这是基本的大纲,HTML:

<div class = "container">
    <div class = "fluid">Glee is very very awesome! I have margins, too!</div>
    <div class = "fixed">Glee is awesome!</div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

.container {
    height: 300px; /*whatever you want*/
    position: relative; /*necessary*/
}
.fluid {
    margin: 10px; /*just an example*/
    position: absolute;
    top: 0;
    bottom: 75px; /*equal to height of bottom fixed-height div*/
    right: 0;
    left: 0;
}
.fixed {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 75px; /*whatever you want*/
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!