使用jQuery设置div高度(拉伸div高度)

51
我有3个带有id的div分别是headercontentfooter。头部和底部具有固定的高度,并且它们被设计为浮动在顶部和底部。我希望使用jquery自动计算中间的content高度。如何实现这一点?
#header {
    height: 35px;
    width: 100%;
    position: absolute;
    top: 0px;
    z-index: 2;
}
#footer {
    height: 35px;
    width: 100%;
    position: absolute;
    bottom: 0px;
    z-index: 2;
}

1
默认情况下,浏览器会自动计算 div 元素的高度以适应内容吗? - John Strickler
页头和页脚有position:fixed属性吗? - Šime Vidas
@Šime,可能是为了适应页眉和页脚之间的空间。 - tomsseisums
自动div高度=100%在Firefox中无法工作。如果我得到px高度,然后减去页眉和页脚的高度,我可以修复这个问题,并设置顶部边距将我的div浮动在页眉和页脚之间 :) - Alfred
@basteralfred 尝试在 html 和 body 标签中添加 height: 100%。然后它应该可以正常工作。 - Mavelo
7个回答

68

你可以这样做:

$(function(){

    var $header = $('#header');
    var $footer = $('#footer');
    var $content = $('#content');
    var $window = $(window).on('resize', function(){
       var height = $(this).height() - $header.height() + $footer.height();
       $content.height(height);
    }).trigger('resize'); //on page load

});

查看fiddle示例: http://jsfiddle.net/maniator/JVKbR/
演示: http://jsfiddle.net/maniator/JVKbR/show/


2
@blasteralfred,较新版本的FF除非用户在其首选项中明确允许,否则不允许窗口操作。 - Mavelo
抱歉,我可能是在查看类似问题的时候添加了那个注释,尝试进行脚本大小调整。PS:确实,虽然它没有修改窗口属性,但我们通过添加监听器来技术性地操作窗口对象...语义学 :P - Mavelo
为什么你不把#content也缓存起来呢? - Shmiddty
哈哈,我没注意到 @Shmiddty ... 现在我开心了 ^_^ - Naftali
@Jules 加法和减法没有运算顺序。无论以何种顺序进行计算,结果都是相同的... - Naftali
显示剩余4条评论

16

正确的方法是使用老牌CSS:

#content{
    width:100%;
    position:absolute;
    top:35px;
    bottom:35px;
}

而且好处是您不需要附加到 window.onresize 事件!所有内容都会随着文档重新流动而调整。这一切只需要四行CSS,价格非常低廉!


这是一个不错的替代方案。我最喜欢Zirak的答案,因为它是OP所要求的(jQuery答案)。 - Benjamin Gruenbaum

15

我能够立即想到的是:

$('#content').height(
    $(window).height() - $('#header').height() - $('#footer').height()
);

你的意思是这个吗?


5
您可以按照以下方式绑定函数,而不是在加载时进行初始化。
$("div").css("height", $(window).height());
$(​window​).bind("resize",function() {
    $("div").css("height", $(window).height());
});​​​​

1
$(document).ready(function(){ contsize();});
$(window).bind("resize",function(){contsize();});

function contsize()
{
var h = window.innerHeight;
var calculatecontsize = h - 70;/*if header and footer heights= 35 then total 70px*/ 
$('#content').css({"height":calculatecontsize + "px"} );
}

0

这应该可以正常工作:

window.addEventListener('resize', function(event) {
    document.querySelector('#middle').style.height = 
    window.innerHeight - $('#header').height() + $('#footer').height() + 'px';
}, true);

0

我认为会起作用。

$('#DivID').height('675px');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接