一、clientHeight与offsetHeight的区别:
- element.clientHeight : 在页面上返回内容的可视高度(不包括边框,边距或滚动条)
- element.offsetHeight:返回,任何一个元素的高度包括边框和填充及滚动条
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style type="text/css">
#div1{
padding:10px;
height:100px;
border:2px solid black;
background-color: red;
box-sizing: border-box;
/*box-sizing:content-box*/
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div id="div1">
</div>
<script type="text/javascript">
var dom=document.getElementById("div1");
console.log("clientHeight",dom.clientHeight);
console.log("offsetHeight",dom.offsetHeight);
</script>
</body>
</html>
上面例子的输出结果为: clientHeight 96 , offsetHeight 100 。
我们在css上做一些小修改,将box-sizing改为content-box。此时结果会发生变化,变化的根本原因在于css盒子模型。当box-sizing为content-box时,即w3c标准,元素的内容区域不包含padding值。所以 此时css中定义的height+padding值会等于 clientHeight(120),height+padding+border等于offsetHeight(124) 。
二、clientHeight和scrollHeight的区别
值得注意的是scrollHeight 没有包含滚动工具条的高度,但scrollHeight是计算整个div中内容的高度(即滚动条拖动后显示的内容),而clientHeight只是记录可视高度。
下面是demo,可copy运行
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style type="text/css">
#div1{
padding:10px;
height:100px;
border:2px solid black;
background-color: red;
/* box-sizing:content-box;*/
box-sizing: border-box;
overflow: scroll;
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div id="div1">
<p>1111</p>
</div>
<script type="text/javascript">
var dom=document.getElementById("div1");
console.log("clientHeight",dom.clientHeight);
console.log("offsetHeight",dom.offsetHeight);
console.log("offsetLeft",dom.offsetLeft);
console.log("offsetParent",dom.offsetParent);
console.log("offsetTop",dom.offsetTop);
console.log("scrollHeight",dom.scrollHeight);
console.log("scrollLeft",dom.scrollLeft);
console.log("scrollTop",dom.scrollTop);
console.log("scrollWidth",dom.scrollWidth);
</script>
</body>
</html>