浏览器大小(宽度和高度)

我试图检测浏览器的当前大小(宽度和高度)。 我知道在jQuery中使用$(document).width and $(document).height ,但我不想将jQuery lib的大小添加到项目中,所以我宁愿使用内置的JavaScript 。 用JavaScript做同样的事情的简短有效的方法是什么?

 // first get the size from the window // if that didn't work, get it from the body var size = { width: window.innerWidth || document.body.clientWidth, height: window.innerHeight || document.body.clientHeight } 
 function getWindowSize(){ var d= document, root= d.documentElement, body= d.body; var wid= window.innerWidth || root.clientWidth || body.clientWidth, hi= window.innerHeight || root.clientHeight || body.clientHeight ; return [wid,hi] } 

IE浏览器是唯一不使用innerHeight和Width的人。

但是没有“标准” – 只是浏览器的实现。

在检查主体之前testinghtml(document.documentElement)clientHeight – 如果它不是0,它是“视口”的高度,body.clientHeight是主体的高度 – 可以大于或小于窗口。

向后模式为根元素返回0,从主体返回窗口(视口)的高度。

与宽度相同。

尝试这个;

  <script type="text/javascript"> winwidth=document.all?document.body.clientWidth:window.innerWidth; winHeight=document.all?document.body.clientHeight:window.innerHeight; alert(winwidth+","+winHeight); </script> 

这是一个代码示例

 function getSize(){ var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var h=window.innerHeight || document.documentElement.clientHeight ||document.body.clientHeight; } 

我的情况使用window.innerWidth涉及build立一个自定义模式popup窗口。 简单地说,用户点击button,popup窗口以浏览器为中心打开,popup后面有一个透明的黑色背景。 我的问题是find浏览器的宽度和高度来创build透明bkgd。

window.innerWidth很好地发现宽度,但记住window.innerWidth and window.innerHeight不补偿滚动条,所以如果你的内容超出了可见内容区域。 我不得不从值中减去17px。

 transBkgd.style.width = (window.innerWidth - 17) + "px"; 

由于该网站的内容总是超出了可见的高度,我不能使用window.innerHeight 。 如果用户向下滚动透明bkgd将在那一刻结束,并且看起来很肮脏。 为了保持透明bkgd一直到我使用document.body.clientHeight的内容的底部。

 transBkgd.style.height = document.body.clientHeight + "px"; 

我testing了IE浏览器,FF,Chrome浏览器的popup窗口,而且看起来很好。 我知道这并没有太多的原来的问题,但我觉得这可能会帮助,如果有人遇到同样的问题,当创build自定义模式popup。