我试图写一个JavaScript函数,以获得当前的浏览器宽度。
我找到了这个:
console.log (document.body.offsetWidth);
但问题是,如果主体宽度为100%,它就会失败。
还有其他更好的功能或解决方案吗?
我试图写一个JavaScript函数,以获得当前的浏览器宽度。
我找到了这个:
console.log (document.body.offsetWidth);
但问题是,如果主体宽度为100%,它就会失败。
还有其他更好的功能或解决方案吗?
当前回答
这很麻烦。我建议跳过这些废话,使用jQuery,它让你只需要执行$(window).width()。
其他回答
2017年更新
我最初的答案写于2009年。虽然它仍然有效,但我想在2017年更新它。浏览器仍然可以有不同的表现。我相信jQuery团队在维护跨浏览器一致性方面做得很好。但是,没有必要包含整个库。在jQuery源代码中,相关的部分可以在dimensions.js的第37行找到。在这里,它被提取和修改为独立工作:
function getWidth() { return Math.max( document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth ); } function getHeight() { return Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight ); } console.log('Width: ' + getWidth() ); console.log('Height: ' + getHeight() );
原来的答案
由于所有浏览器的行为都不同,因此需要首先测试值,然后使用正确的浏览器。这里有一个函数为你做这件事:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
if (document.body) {
return document.body.clientWidth;
}
}
身高也是一样:
function getHeight() {
if (self.innerHeight) {
return self.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
if (document.body) {
return document.body.clientHeight;
}
}
在脚本中使用getWidth()或getHeight()调用这两个函数。如果没有定义浏览器的本机属性,它将返回undefined。
这很麻烦。我建议跳过这些废话,使用jQuery,它让你只需要执行$(window).width()。
下面是上面函数的一个简短版本:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
else if (document.documentElement && document.documentElement.clientHeight){
return document.documentElement.clientWidth;
}
else if (document.body) {
return document.body.clientWidth;
}
return 0;
}
var w = window.innerWidth;
var h = window.innerHeight;
var ow = window.outerWidth; //including toolbars and status bar etc.
var oh = window.outerHeight;
两者都返回整数并且不需要jQuery。跨浏览器兼容的。
我经常发现jQuery返回width()和height()的无效值。
从W3schools和它的跨浏览器回到IE的黑暗时代!
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
alert("Browser inner window width: " + w + ", height: " + h + ".");
</script>
</body>
</html>