Javascript 跨多个浏览器一致地获取可用的浏览器窗口大小(clientHeight/clientWidth)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4976936/
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
Get the available browser window size (clientHeight/clientWidth) consistently across multiple browsers
提问by
I would like a method of getting the available window size across multiple browsers withoutusing jQuery/Mootools/any third-party library dependencies. I've done a little research on this but half the things I've come across talk about Netscape Navigator...
我想要一种在不使用 jQuery/Mootools/任何第三方库依赖项的情况下跨多个浏览器获取可用窗口大小的方法。我对此做了一些研究,但我遇到的一半事情都在谈论 Netscape Navigator...
Just wondering if someone out there has more recent advice.
只是想知道是否有人在那里有更新的建议。
采纳答案by gblazex
usage
用法
var width = getWindowSize().width;
code
代码
var getWindowSize = (function() {
var docEl = document.documentElement,
IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0;
// Used to feature test Opera returning wrong values
// for documentElement.clientHeight.
function isDocumentElementHeightOff () {
var d = document,
div = d.createElement('div');
div.style.height = "2500px";
d.body.insertBefore(div, d.body.firstChild);
var r = d.documentElement.clientHeight > 2400;
d.body.removeChild(div);
return r;
}
if (typeof document.clientWidth == "number") {
return function () {
return { width: document.clientWidth, height: document.clientHeight };
};
} else if (IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) {
var b = document.body;
return function () {
return { width: b.clientWidth, height: b.clientHeight };
};
} else {
return function () {
return { width: docEl.clientWidth, height: docEl.clientHeight };
};
}
})();
Note: The dimensions cannot be determined accurately until after the document has finished loading.
注意:在文档完成加载之前,无法准确确定尺寸。
回答by Dave
This is not a perfect solution, but it is lightweight & suitable for most purposes:
这不是一个完美的解决方案,但它是轻量级的并且适用于大多数用途:
var WX,WY;
if( window.innerWidth )
{
WX = window.innerWidth;
WY = window.innerHeight;
} else {
WX = document.body.clientWidth;
WY = document.body.clientHeight;
}
回答by Steven Vachon
For modern browsers:
对于现代浏览器:
document.documentElement.clientHeight
is all you need.
是你所需要的全部。