浏览器大小(宽度和高度)
我试图检测浏览器的当前大小(宽度和高度)。我知道在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
}
试试这个;
<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 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和宽度的唯一部分。
但是没有标准的浏览器实现。
在检查主体之前测试html(document.documentElement)clientHeight- 如果它不是0,它是'视口'的高度,body.clientHeight是主体的高度 - 可以更大或小于窗户。
向后模式为根元素返回0,并从正文中返回窗口(视口)高度。
与宽度相同。
我的案例使用window.innerWidth
涉及建立一个自定义模态弹出窗口。简单地说,用户点击按钮,弹出窗口在浏览器中居中打开,弹出后面有一个透明的黑色背景。我的问题是找到浏览器的宽度和高度来创建透明bkgd。
window.innerWidth
很好地发现宽度,但记住window.innerWidth and window.innerHeight
不补偿滚动条,所以如果你的内容超出了可见内容区域。我不得不从该值中减去17px。
transBkgd.style.width = (window.innerWidth - 17) + "px";
由于该网站的内容总是超出了可见高度,因此我无法使用window.innerHeight
。如果用户向下滚动透明背景,那么会在该点结束,看起来很肮脏。为了保持透明bkgd一直到我使用的内容的底部document.body.clientHeight
。
transBkgd.style.height = document.body.clientHeight + "px";
我测试了IE,FF,Chrome中的弹出窗口,它看起来很好。我知道这并不太符合原来的问题,但我认为这可能会有所帮助,如果有人在创建自定义模式弹出窗口时遇到同样的问题。
下面是一个代码示例
function getSize(){
var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h=window.innerHeight || document.documentElement.clientHeight ||document.body.clientHeight;
}
在这已经回答了相当不错:http://stackoverflow.com/questions/1766861/find-the-exact-height-and-width-of-the -viewport-in-a-cross-browser-way-no-protot – vsync 2010-03-23 14:32:29