关于offsetTop offsetHeight clientHeight scrollHeight scrollTop的区别研究
我是以chrome浏览器做的研究。
先看一段代码:
<script>window.addEventListener('DOMContentLoaded',function(){var node1 = document.querySelector('#father');var node2 = document.querySelector('#child');console.log('offsetTop==offsetHeight==scrollTop==scrollHeight==clientHeight');console.log('father: '+node1.offsetTop+'=='+node1.offsetHeight+'=='+node1.scrollTop+'=='+node1.scrollHeight+'=='+node1.clientHeight);console.log('child: '+node2.offsetTop+'=='+node2.offsetHeight+'=='+node2.scrollTop+'=='+node2.scrollHeight+'=='+node2.clientHeight);/**offsetTop:是本元素距上层元素且元素设置了postion=relative的距离,如果所有父级元素都没有设置postion。就是距body的距离。计算:offsetTop = margin+topoffsetHeight:是本元素底部到本元素顶部的距离。计算:offsetHeight = content+padding+borderscrollTop:是浏览器可视窗口顶端距页面顶部的距离。计算: 无scrollHeight: 是容器内所有元素及子元素的高度之和,如果没有子元素,即为自身高度+padding。计算: 有子元素:包括所有子元素的(content+padding+border+margin)之和无子元素:content+paddingclientHeight: 是自身容器的高度。除去滚动条的宽度。计算: content.height+padding-滚动条的宽度*/}); </script> </head> <body><div style="position:relative;" id="superFather"><div style="width:500px;height:1000px;background:red;overflow:auto;" id="father"><!-- <div style="width:500px;height:500px;background:green;padding:10px;margin:60px;border:5px solid #2EE008; opacity:0.5;position:absolute;top:50px;" id="child"></div> --><div style="width:800px;height:500px;background:green;padding:10px;margin:60px;border:5px solid #2EE008; opacity:0.5;" id="child"></div><div style="width:800px;height:500px;background:green;padding:10px;margin:60px;border:5px solid #2EE008; opacity:0.5;" id="child"></div><div style="width:800px;height:500px;background:green;padding:10px;margin:60px;border:5px solid #2EE008; opacity:0.5;" id="child"></div></div> </div></body>
所以,根据上面的解释输出结果为:
offsetTop: farther=0,child = margin(60)
offsetHeight: farther = content(1000),child = content(500)+padding(20)+border(10)
scrollTop: 0,0
scrollHeight: farther=500*3+60*4+20*3+10*3,500+10*2
clientHeight: 100-17,500+10*2
所以整体输出:
总结一下算法:
offsetHeight:content+padding+border
offsetTop: margin+top
scrollHeight/clientHeight: 子元素没有超出情况下:content+padding 只是clientHeight在有滚动条的情况下,是要去除滚动条宽度。子元素超出之后:所有子元素的(content+padding+border+margin)之和
scrollTop:浏览器可视区域顶部到页面顶部的距离
参考链接:http://www.softwhy.com/forum.php?mod=viewthread&tid=8298
转载于:https://www.cnblogs.com/freefish12/p/5568043.html
总结
以上是生活随笔为你收集整理的关于offsetTop offsetHeight clientHeight scrollHeight scrollTop的区别研究的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: [AngularJS学习笔记] 基础学习
- 下一篇: PAT天梯赛练习题——L3-005. 垃