日期:2014-05-16  浏览次数:20323 次

javascript获取浏览器宽度和高度

测试浏览器及版本:IE8、FF5、Chrome12

屏幕分辨率:1366 x 768

文档声明:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

?

1.获取屏幕分辨率(所有浏览器一致):

屏幕横向分辨率:window.screen.width?? 1366

屏幕纵向分辨率:window.screen.height?? 768

?

2.网页可见区域宽度和高度

宽度:document.body.clientWidth

高度:document.body.clientHeight

?

有文档声明时:宽度为网页可见区域高度,高度可能小于可见区高度

无文档声明时:宽度为网页可见区域高度,高度大于等于可见区高度

?

3.屏幕可用工作区域宽度和高度

宽度:window.screen.availWidth?? 屏幕横向分辨率-任务栏宽度(如果任务栏在左侧或右侧)

高度:window.screen.availHeight? 屏幕纵向分辨率-任务栏高度(如果任务栏在顶部或底部)

?

4网页正文宽度和高度

宽度:document.body.scrollWidth

高度:document.body.scrollHeight

?

有文档声明:IE8和FF5高度可能小于可见区域高度,Chrome12大于等于可见区域高度

无文档声明:IE8高度可能小于可见区域高度,FF5和Chrome12大于等于可见区域高度

?

5.网页可见区域宽度和高度(包括边线)

宽度:document.body.offsetWidth

高度:document.body.offsetHeight

?

有文档声明:全部可能小于可见区域高

无文档声明:FF5高度可能小于可见区域高度,IE8和Chrome12大于等于可见区域高度

?

有文档声明的测试代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>测试1</title>
<script type="text/javascript">
function show(){
    var s = "";
	s += "网页可见区域宽度:"+document.body.clientWidth;
	s += "\n网页可见区域高度:"+document.body.clientHeight;
	s += "\n网页可见区域宽度(包括边线):"+document.body.offsetWidth;
	s += "\n网页可见区域高度(包括边线):"+document.body.offsetHeight;
	s += "\n网页正文宽度:"+document.body.scrollWidth;
	s += "\n网页正文高度:"+document.body.scrollHeight;
	s += "\n屏幕可用工作区域宽度:"+window.screen.availWidth;
	s += "\n屏幕可用工作区域高度:"+window.screen.availHeight;
	s += "\n屏幕分辨率宽度:"+window.screen.width;
	s += "\n屏幕分辨率高度:"+window.screen.height;
	alert(s);
}
</script>
</head>

<body style="margin:0;border:0">
<div style="width:2000px;height:90px;margin:0">
<a onclick="show()" href="#">点击</a>
</div>
</body>
</html>

?

无文档声明的测试代码

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>测试2</title>
<script type="text/javascript">
function show(){
    var s = "";
	s += "网页可见区域宽度:"+document.body.clientWidth;
	s += "\n网页可见区域高度:"+document.body.clientHeight;
	s += "\n网页可见区域宽度(包括边线):"+document.body.offsetWidth;
	s += "\n网页可见区域高度(包括边线):"+document.body.offsetHeight;
	s += "\n网页正文宽度:"+document.body.scrollWidth;
	s += "\n网页正文高度:"+document.body.scrollHeight;
	s += "\n屏幕可用工作区域宽度:"+window.screen.availWidth;
	s += "\n屏幕可用工作区域高度:"+window.screen.availHeight;
	s += "\n屏幕分辨率宽度:"+window.screen.width;
	s += "\n屏幕分辨率高度:"+window.screen.height;
	alert(s);
}
</script>
</head>

<body style="margin:0;border:0">
<div style="width:2000px;height:90px;margin:0">
<a onClick="show()" href="#">点击</a>
</div>
</body>
</html>

?