jQuery 如何获取body元素的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/806402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:49:42  来源:igfitidea点击:

How to get the height of a body element

jquerycss

提问by Shiva Srikanth Thummidi

Here the total height of all <div>'s are 900 pixels, but the jQuery function returns the height of the body as 577 pixels. (If I remove the body CSS, it's working).

这里 all 的总高度为<div>900 像素,但 jQuery 函数返回 body 的高度为 577 像素。(如果我删除了正文 CSS,它就可以工作)。

Is there a solution for this problem?

这个问题有解决方案吗?

$j(function() {
    alert($j("body").height());
})

html, body {
    height:100%;
}

<div style="height:200px">header</div>
<div style="height:500px">content</div>
<div style="height:200px">footer</div>

回答by OderWat

Simply use

只需使用

$(document).height() // - $('body').offset().top

and / or

和/或

$(window).height()

instead of $('body').height();

代替 $('body').height();

回答by Rafael

Set

html { height: 100%; }
body { min-height: 100%; }

instead of height: 100%.

而不是height: 100%.

The result jQuery returns is correct, because you've set the height of the body to 100%, and that's probably the height of the viewport. These three DIVs were causing an overflow, because there weren't enough space for them in the BODY element. To see what I mean, set a border to the BODY tag and check where the border ends.

jQuery 返回的结果是正确的,因为您已将主体的高度设置为 100%,而这可能就是视口的高度。这三个 DIV 导致溢出,因为 BODY 元素中没有足够的空间容纳它们。要明白我的意思,请为 BODY 标记设置一个边框并检查边框的结束位置。

回答by Mark

$(document).height() seems to do the trick and gives the total height including the area which is only visible through scrolling.

$(document).height() 似乎可以解决问题,并给出包括仅通过滚动可见的区域的总高度。

回答by Owain Glynd?r

We were trying to avoid using the IE specific

我们试图避免使用特定于 IE 的

$window[0].document.body.clientHeight 

And found that the following jQuery will not consistently yield the same value but eventually does at some point in our page load scenario which worked for us and maintained cross-browser support:

并发现以下 jQuery 不会始终如一地产生相同的值,但最终会在我们的页面加载场景中的某个时刻产生,这对我们有用并保持跨浏览器支持:

$(document).height()

回答by Fenton

I believe that the body height being returned is the visible height. If you need the total page height, you could wrap your div tags in a containing div and get the height of that.

我相信返回的身体高度是可见高度。如果您需要总页面高度,您可以将 div 标签包装在一个包含 div 中并获取其高度。