document.body.clientHeight和document.documentElement.clientHeight區別

admin發表於2017-04-16

本章節介紹一下document.body.clientHeight和document.documentElement.clientHeight的區別。

這裡都已html頂部帶有<!doctype html>考慮,因為現在誰寫頁面還會不寫這個命令呢。

看一段程式碼例項:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin:0px;
  padding:0px;
}
#antzone {
  width:200px;
  height:100px;
  background:#ccc;
  margin:50px auto;
  position:absolute;
}
</style> 
<script type="text/javascript"> 
window.onload = function () {
  var bodyH = document.body.clientHeight;
  var documentElementhH = document.documentElement.clientHeight;
  var str = "bodyH:" + bodyH + "<br/>";
  str = str + "documentElementhH:" + documentElementhH;
  antzone.innerHTML = str;
}
</script> 
</head>   
<body> 
<div id="antzone"></div>
</body> 
</html>

上面的程式碼中,body是沒有高度的,document.body.clientHeight返回值是0,document.documentElement.clientHeight返回的是頁面可見區域的高度,再來看一段程式碼例項:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin:0px;
  padding:0px;
}
body {
  height:1500px;
}
#antzone {
  width:200px;
  height:100px;
  background:#ccc;
  margin:50px auto;
  position:absolute;
}
</style> 
<script type="text/javascript"> 
window.onload = function () {
  var bodyH = document.body.clientHeight;
  var documentElementhH = document.documentElement.clientHeight;
  var str = "bodyH:" + bodyH + "<br/>";
  str = str + "documentElementhH:" + documentElementhH;
  antzone.innerHTML = str;
}
</script> 
</head>   
<body> 
<div id="antzone"></div>
</body> 
</html>

設定body的高度,document.body.clientHeight返回值就是這個高度,document.documentElement.clientHeight返回值依然是可見區域的高度。

相關文章