document.body.clientHeight和document.documentElement.clientHeight区别

快乐打工仔 分类:实例代码

本章节介绍一下document.body.clientHeight和document.documentElement.clientHeight的区别。

这里都已html顶部带有<!doctype html>考虑,因为现在谁写页面还会不写这个命令呢。

看一段代码实例:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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返回的是页面可见区域的高度,再来看一段代码实例:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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返回值依然是可见区域的高度。

document.body.clientHeight和document.documentElement.clientHeight区别,这样的场景在实际项目中还是用的比较多的,关于document.body.clientHeight和document.documentElement.clientHeight区别就介绍到这了。

document.body.clientHeight和document.documentElement.clientHeight区别属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容