如何使用JavaScript代码获取浏览器宽度?

我正在尝试编写一个JavaScript函数来获取当前的浏览器宽度。

我发现这一个:

javascript:alert(document.body.offsetWidth); 

但是,如果身体宽度达到100%,就会失败。

有没有其他更好的function或解决方法?

这是一个痛苦的屁股 。 我build议跳过废话,并使用jQuery ,它可以让你做$(window).width()

2017年更新

我原来的答案是在2009年写的。虽然它仍然有效,我想更新它在2017年。浏览器仍然可以有不同的行为。 我相信jQuery团队在维护跨浏览器一致性方面做得非常好。 但是,没有必要包括整个图书馆。 在jQuery源代码中,可以在dimensions.js的第37行find相关部分。 在这里它被提取和修改为独立工作:

 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() ); 
 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()的无效值

为什么没有人提到matchMedia?

 if (window.matchMedia("(min-width: 400px)").matches) { /* the viewport is at least 400 pixels wide */ } else { /* the viewport is less than 400 pixels wide */ } 

没有testing那么多,但testing与Android默认和Android的Chrome浏览器,桌面铬,到目前为止,它看起来像它运作良好。

当然,它不返回数值,但返回布尔值 – 如果匹配或不匹配,所以可能不完全适合这个问题,但这就是我们想要的,可能是问题的作者想要的。

从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> 

这里是上面介绍的function的一个较短的版本:

 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; }