关于javascript:dom元素各种高度

获取body的滚动高度

环境:chrome浏览器

  1. 有h5文档申明:<!DOCTYPE html> Standard 模式下
    document.body.scrollTop 始终为0
    document.documentElement.scrollTop 获取正确
    window.pageYOffset 获取正确
  2. 无文档申明
    document.body.scrollTop 获取正确
    document.documentElement.scrollTop 始终为0
    window.pageYOffset 获取正确

兼容写法:let height = document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset

dom对象中六种高度辨别

// 示例 屏幕宽度414, div宽度100%
<body>
  <div id="out" style="margin-top: 100px;height: 300px;padding: 20px;border: 10px solid red;overflow: scroll">
    <div id="inner" style="height: 500px;"></div>
  <div>
<body>
// p-padding ,b-border, h-height, w-width
1. height
document.querySelector('#out').clientHeight    340  300(h) + 20(p)*2 
document.querySelector('#out').offsetHeight    360  300(h) + 20(p)*2  + 10(h)*2
document.querySelector('#out').scrollHeight    540  500(h) + 20(p)*2
 
2. width
document.querySelector('#out').clientWidth    394  414(w) - 10(b)*2 
document.querySelector('#out').offsetWidth    414  414(w)
document.querySelector('#out').scrollWidth    394  414(w) - 10(b)*2 

3.top 向下滚动inner肯定100px
document.querySelector('#out').clientTop    10   边框10
document.querySelector('#out').offsetTop    100  margin 100
document.querySelector('#out').scrollTop    100  滚动 100

document.querySelector('#inner').clientTop    0       0
document.querySelector('#inner').offsetTop    130      100 + 20 + 10
document.querySelector('#inner').scrollTop    0        无滚动

3.left 向下滚动inner肯定100px
document.querySelector('#out').clientLeft   10   边框10
document.querySelector('#out').offsetLeft   0  
document.querySelector('#out').scrollLeft      0  

总结

  1. clientHeight 元素高度(不含boder)
  2. offsetHeight 元素高度(含boder)
  3. scrollHeight 滚动元素总高度
  4. scrollTop 滚动高度(暗藏局部)
  5. clientTop 上边框高度
  6. offsetTop 绝对于offsetParent的高度。offsetParent:间隔元素最近的一个具备定位的祖宗元素(relative,absolute,fixed),若祖宗都不符合条件,offsetParent为body。
  7. 当dom元素为doument.body或者document.documentElement时,clientHeight 等于屏幕高度。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理