Tuesday, November 28, 2006

再谈:通过javascript取的浏览器客户区的尺寸


  上次说到"通过javascript取的浏览器客户区的尺寸",是通过document.body.clientWidth 和 document.body.clientHeight来去客户区的高和宽,刚刚的实践中,发现在firefox下是无效的,几经试验发现了一个更好的方法,通过documentElement.clientWidth 和 document.documentElement.clientHeight来取客户区的高和宽。





<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title id="aaa">DIV布局</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>

<style type="text/css">

body {
BACKGROUND: #000000;
MARGIN: 0px 0px 0px 0px;
TEXT-ALIGN: center;
width: 100%;
height: 100%
}

#demo {
BACKGROUND: #a5d854 ;
MARGIN: 0px 0px 0px 0px;
width: 2000px;
height: 800px
}

</style>
<script type="text/javascript">
function sizeOfBody(x)
{
var ss = "";
ss = "size of body(" + x + "): width:" + document.documentElement.clientWidth + " height:" + document.documentElement.clientHeight;
alert(ss);
}
</script>
</head>
<body onload="sizeOfBody('onload')">
<script type="text/javascript">
sizeOfBody("begin of body");
</script>
<div id="demo">

</div>
<script type="text/javascript">
sizeOfBody("end of body");
</script>
</body>
</html>





执行的结果先后为:
  1. size of body(begin of body): width:1004 height:617
  2. size of body(end of body): width:1004 height:617
  3. size of body(onload): width:1004 height:617



  用这个有一个好处:无论在什么时机调用都是准确的客户区size,而且在firefox和IE下通吃。



No comments: