设置元素min-height等于文档的可见部分

时间:2012-09-22 18:06:47

标签: javascript jquery

我有一个页面,至少包含一个标题和一个容器div 我想为容器div设置min-height以覆盖文档的可见部分 (我不想将其修复为100%)

所以我认为我可以通过元素高度和顶部填充以及上边距

获得文档高度
function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

$(document).ready(function(e) {

    var h = getDocHeight();
    var hedaer = $('.header').height();
    var c = $('.container').css('height') ;
    var m = $('.container').css('padding-top') ;
    var p = $('.container').css('margin-top') ;
    var n = parseInt(h) -  parseInt(c) -   parseInt(m) - parseInt(p) - parseInt(hedaer) ;
    var n = n +  parseInt(c)   ;
    $('.content').css('min-height' , n+'px');

});

但我总是或多或少地结束 我的容器里面还有很多其他元素,它们有自己的高度,填充和边距,这让我很难想到它们

有没有更简单的方法呢?

1 个答案:

答案 0 :(得分:1)

不完全确定你想要什么,我的答案可能不合适取决于你所针对的浏览器,但显示:框可能是解决方案(webkit的代码,以适应其他供应商的前缀):

<div class="container">
  <div class="header">blue</div>
  <div class="content">red</div>
</div>

和css

.container {
  /*create a vertical box*/
  display: -webkit-box;
  -webkit-box-orient: vertical;
  /*ensure it takes of all available width and height in my fiddle :-D */
  position: fixed;
  top:0; bottom: 0; left: 0; right: 0;
}
/*so that we see something*/
.header, .content {background: blue;margin: 20px;padding: 40px;}
.content {
  margin: 20px;
  padding: 40px;
  background: red;
  /*this div will have all available height in his parent, 
    minus what's already taken, with the beauty of box-flex */
  -webkit-box-flex: 1;
}

...仍然是一个非常不稳定且不受支持的规范,但我认为值得一提。你可以在这里看到它(使用chrome或safari)http://jsfiddle.net/S6F3S/1/