使用JS计算Div高度

时间:2012-11-15 03:24:11

标签: javascript jquery css

我正在使用一些javascript来计算页面的高度,然后在div上设置最小高度。这样做的原因是将页脚推到页面底部,以查找内容不足的页面。我的问题是最小高度大约30-40 px因此导致滚动条。 (注意:出于各种原因,我没有使用粘性页脚等解决方案,而是更喜欢这种解决方案。)

这是我的代码:

JS

$(function() {
  var height = $(window).height() - ($("header").outerHeight() + $("footer").outerHeight() );
 $("#page-content").css("min-height",height+"px");
});

HTML

 <header class="container">
 <div id="menu" class="row">
   <!-- Content -->
 </div>
</header>

<div id="page-content">
  <!-- Content --> 
</div>

<footer>
  <!-- Content --> 
</footer>

我认为问题在于我的CSS。例如,我在标题中有一个边距:

#menu{
 margin: 5px auto 10px;
}

如果删除该代码,它会稍微减少滚动条。 (我在页面上设置了其他页边距,因此只更改此页面将无法作为解决方案)。

如何重新编写JS代码以考虑标题和其他部分的边距?

5 个答案:

答案 0 :(得分:1)

<header>框的高度不会反映孩子#menu的边距,因为它们都是正常的框元素,如果#page-content有边距,它们会与#menu重叠1}}的边距,在这种情况下,标题的高度将包含内容高度的某些部分,这是没有意义的。

问题是边距崩溃:http://www.w3.org/TR/css3-box/#collapsing-margins

正如该页面所解释的那样,您可以通过以下几种方式告诉浏览器不要折叠边距:

  • display: inline-block;添加到您的#menu { }规则(我的第一个建议)
  • overflow: hidden;添加到header { }(如果您遇到对齐问题,可能会提出更好的建议)
  • 让您的<header>绝对定位,或将其浮动。或者这样做#menu里面。

或者如果你想要破解,你可以手动计算标题高度:

var header_height = $("header").outerHeight() +
   parseInt($("header").children().css('margin-top'), 10) +
   parseInt($("header").children().css('margin-bottom'), 10);

现在我考虑一下,这是有道理的,我认为css规范正在做正确的事。

更新:http://jsfiddle.net/HzBSz/2/

另见:Outer element margin not equal to inner element margin

答案 1 :(得分:1)

由于某种原因,JS没有计算边际。我添加了页眉和页脚中的边距,总计45px。因此,脚本现在看起来像这样:

$(function() {
  var height = $(window).height() - ($("header").outerHeight() + 
               $("footer").outerHeight() + 45   ); 
  $("#page-content").css("min-height",height+"px"); 
});

我添加了45px,脚本现在可以正常运行。

答案 2 :(得分:0)

为什么不手动将页脚放在底部?我的意思是,我知道你说你不喜欢,但为什么?如果您希望它始终存在,请执行

position:relative;
bottom:0;

如果您希望它与页面的其余部分一起滚动(听起来像你可能),请使用

position:absolute;

代替。 这是一种比动态插入虚拟内容以推动页脚更好的方法。

答案 3 :(得分:0)

也许你看看这个 http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page 可以解决你的问题。

答案 4 :(得分:0)

为所有元素尝试.outerHeight(true)而不是.height()或.outerHeight():

$(function() {
  var height = $(window).outerHeight(true) - ($("header").outerHeight(true) + $("footer").outerHeight(true) );
 $("#page-content").css("min-height",height+"px");
});

.height() - 返回元素的高度,不包括填充,边框和边距。

.innerHeight() - 返回元素的高度,包括填充但不包括边框和边距。

.outerHeight() - 返回div的高度,包括边框,但不包括边距。

.outerHeight(true) - 返回div的高度,包括margin。

相关问题