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

时间:2010-03-18 23:18:59

标签: javascript jquery browser

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

5 个答案:

答案 0 :(得分:80)

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

答案 1 :(得分:8)

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的人。

但是没有'标准' - 只是浏览器实现。

在检查身体之前测试html(document.documentElement)clientHeight- 如果它不是0,则它是'viewport'的高度,body.clientHeight是body的高度 - 可以大于或小于窗口。

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

与宽度相同。

答案 2 :(得分:3)

试试这个;

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

答案 3 :(得分:3)

这是一个代码示例

function getSize(){

var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

var h=window.innerHeight || document.documentElement.clientHeight ||document.body.clientHeight;


}

答案 4 :(得分:2)

我使用window.innerWidth的案例涉及构建自定义模式弹出窗口。简而言之,用户点击按钮,弹出窗口在浏览器中心打开,弹出窗口后面有一个透明的黑色bkgd。我的问题是找到浏览器的宽度和高度来创建透明的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";

我测试了IE,FF,Chrome中的弹出窗口,它看起来很好。我知道这并没有太多地遵循原始问题,但我认为如果其他人在创建自定义模式弹出时遇到同样的问题可能会有所帮助。