2014-02-05 117 views
0

我试图创建一个总是延伸到页面底部的<div>。一个simliar问题在这里讨论:https://stackoverflow.com/questions/16821721/extend-div-to-bottom-of-page 但是,我想只有使用div本身。我的做法是下面的JavaScript代码(这将是每个窗口大小时执行):使div延伸到页面的底部

var total_height = $(window).height(); 
var container = $("div#container:first")[0]; 

var rect = container.getBoundingClientRect(); 

var remaining_height = total_height - rect.top; 

container.style.height = "" + remaining_height + "px"; 

的问题是高度不采取填充/利润率考虑这样的股利是有点偏大。我想设置高度,使offsetHeight等于remaining_height,但我不知道如何才能达到效果...任何想法?与JS/jQuery的

LIVE DEMO

或者:

+3

'#container:first'意味着您有多个具有相同ID名称的'ID'元素**这是错误的** –

+0

也许'#container div:first'?! – mehdi

+0

http://api.jquery.com/outerheight/就像'.outerHeight(true)'? – loveNoHate

回答

0

您可以通过模仿所需#container背景...其实它设置为给BODY元素做纯HTML CSS &

LIVE DEMO

var windowHeight = $(window).height(); 
var $cont = $('#container'); // or use #containerParent if you have paddings 
var contTop = $cont[0].getBoundingClientRect().top; 
$cont.height(windowHeight - contTop); 

,如果你不希望有一个包装,你想垫衬适用于#container
比去为它:

LIVE DEMO

var windowHeight = $(window).height(); 
var $cont = $('#container'); 
var contH = $cont.outerHeight(true) - $cont.height(); // paddings, borders... 
var contT = $cont[0].getBoundingClientRect().top; 
$cont.height(windowHeight - contT - contH); 
+0

你不理解我......在你的CSS容器中添加'padding:10px;'到你的#容器中,你会看到问题... – hfhc2

+0

@ hfhc2将#container包装到父元素中,并将我的代码应用到该元素。那简单的 –

+0

@ hfhc2我已经在演示中清楚地向你展示了唯一具有填充的元素是内容容器'.centered' –

0

的的offsetHeight就是价值你在将元素的高度添加到它的填充顶部和填充底部属性以及边框值时获取。

所以你不能只减去填充的顶部和底部值,并从remaining_height值的边界底部/顶部值来获得你之后的高度?

+0

再一次,如果你可以得到这个工作http://jsbin.com/sodu/3/edit我是耳朵。但它似乎不是填充问题... – hfhc2

0

在你的问题,你说你想要一个<div>延伸到页面的底部,但您的计算涉及使用$(window).height();返回浏览器窗口(source)的高度。

虽然使用视口尺寸可能适用于某些情况,但例如,如果在视口不在文档顶部时重新加载页面,它可能会失败。

随着在考虑,这里是我使用的代码:

$(function() { 

    //get the height of the document 
    var docHeight = $(document).height(); 
    var extended = $("#extended"); 
    //offset.top gets the top position related to the document, using border-box. 
    var top = extended.offset().top; 
    //get the margin, if any. 
    var marginBottom = parseInt(extended.css("margin-bottom"), 10); 
    //set the height so that the bottom margin (or the element) is on the bottom. 
    extended.outerHeight(docHeight - top - marginBottom); 

}); 

LIVE DEMO

这工作如果元素填充,边框和/或保证金。