关于javascript:dom元素各种高度

5次阅读

共计 1675 个字符,预计需要花费 5 分钟才能阅读完成。

获取 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 等于屏幕高度。
正文完
 0