Javascript 获取网页正文或窗口的高度和宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3288397/
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-23 04:02:51  来源:igfitidea点击:

Getting height and width of body or window of web page

javascriptjqueryhtml

提问by Ash Burlaczenko

Depending on which mode of IE8 i'm in (quirks or standard) i get different values for the height and width. I've tried standard javascript and jquery but both return different results.

根据我使用的 IE8 模式(怪癖或标准),我得到不同的高度和宽度值。我尝试过标准的 javascript 和 jquery,但都返回不同的结果。

In Quirks

在怪癖中

$('body').width = 1239  
$('body').height = 184  
document.body.clientWidth = 1231  
document.body.clientHeight = 176  

In standards

在标准中

$('body').width = 1260  
$('body').height = 182  
document.body.clientWidth = 1254  
document.body.clientHeight = 176

Any ideas how to get a value unchanged by the mode of IE8.

任何想法如何获得 IE8 模式不变的值。

Thanks in adv.

感谢广告。

采纳答案by balupton

Perhaps the issue is due to the scrollbars being included in the width and height regardless of whether or not they are there. I don't have IE (on a mac) so can't verify.

也许问题是由于滚动条包含在宽度和高度中,无论它们是否存在。我没有 IE(在 Mac 上)所以无法验证。

However, I can tell you what does work as in my project jQuery LightboxI have no such issue. We use the following code in it:

但是,我可以告诉你什么在我的项目jQuery Lightbox中起作用,我没有这样的问题。我们在其中使用以下代码:

// Make the overlay the size of the body
var $body = $(this.ie6 ? document.body : document); // using document in ie6 causes a crash
$('#lightbox-overlay').css({
 width:  $body.width(),
 height:  $body.height()
});

// ... some code ...

// Get the window dimensions
var $window = $(window);
var wWidth  = $window.width();
var wHeight = $window.height();

And the overlay displays correctly. I would trust jQuery's result of the width and height compared to that of the native result, as jQuery should naturally be taking into account any quirks with the browser.

并且叠加显示正确。与本机结果相比,我相信 jQuery 的宽度和高度结果,因为 jQuery 自然应该考虑浏览器的任何怪癖。

It is important to note that the lightbox script above tends to prefer $(document)over $(document.body)for some reason - I can't remember sorry :O - so perhaps this solves the issue as well?

这是要注意重要的是上面的灯箱脚本更倾向于使用$(document)$(document.body)某种原因-我不记得遗憾:O型-也许这可以解决问题呢?

回答by gearsdigital

Just a quickshot. Try to give your body #page:

只是一个速记。尝试给你的身体#page:

function getPageHeight() {
    var pageHeight = document.getElementById('page').offsetHeight;
    var pageWidth = document.getElementById('page').offsetWidth;

    alert(pageHeight);
    alert(pageWidth);
}

回答by kaleazy

Try this:

尝试这个:

var viewport = {
    width : $(window).width(),
    height : $(window).height()
};

var width = viewport.width;
var height = viewport.height;