Javascript 使div延伸到页面底部
我正在尝试创建一个始终延伸到页面底部的Javascript 使div延伸到页面底部,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我正在尝试创建一个始终延伸到页面底部的。这里讨论了一个类似的问题: 但是,我只想使用div本身。我的方法是使用以下javascript代码(每次调整窗口大小时都会执行): 问题是高度没有考虑填充/边距,因此div有点太大。我想设置高度,使离地高度等于剩余高度,但我不确定如何才能达到效果。。。有什么想法吗?你可以通过模仿所需的#容器背景,用简单的HTML和CSS来实现。。。实际将其设置为主体元素: var windowHeight = $(window).height(); var $cont
。这里讨论了一个类似的问题:
但是,我只想使用div本身。我的方法是使用以下javascript代码(每次调整窗口大小时都会执行):
问题是高度没有考虑填充/边距,因此div有点太大。我想设置高度,使离地高度等于剩余高度,但我不确定如何才能达到效果。。。有什么想法吗?你可以通过模仿所需的
#容器
背景,用简单的HTML和CSS来实现。。。实际将其设置为主体
元素:
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);
或者使用JS/jQuery:
如果您不想要包装纸,并且您想要将填充物应用于#容器
然后去做:
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);
当您将元素的高度添加到元素的padding top和padding bottom属性以及边框值时,offsetHeight就是您得到的值
那么,你不能从剩余的高度值中减去padding top和bottom值以及border bottom/top值来得到你想要的高度吗?在你的问题中,你说你想将
扩展到页面底部,但是你的计算涉及到使用$(window).height()代码>返回浏览器视口的高度()
在某些情况下,使用视口标注可能会起作用,但如果在视口不在文档顶部时重新加载页面,则可能会失败
考虑到这一点,以下是我使用的代码:
$(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);
});
如果元素具有填充、边框和/或边距,则此操作有效。#container:first
意味着您有多个ID名称相同的元素,这可能是错误的#container div:first
?!就像在.outerHeight(true)
中一样,outerHeight()
获取外部高度。我想设置它。另外,忘记:first
,那是错误的,你不理解我。。。添加填充:10px
到css中的#容器
,您将看到问题…@hfhc2将您的#容器包装到父元素中,并将我的代码应用到该元素。那个simple@hfhc2在演示中,我已经清楚地向您展示了唯一具有填充的元素是内容容器。以内容容器为中心的@hfhc2用您需要的内容编辑了我的答案(希望如此)。我明白您的意思。我的问题是:我有一个div代理,上面拿着一个菜单栏,另一个拿着实际内容。我的内容比我能显示的要多,所以我在content div中添加了“overflow-y:scroll;”。我想确保整个文档在content div中没有滚动条。这仍然不太管用。但是填充物似乎不是问题。。。看这里:再说一次,如果你能让这个工作,我洗耳恭听。但似乎这不是一个关于填充的问题。。。
$(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);
});