获取body的滚动高度
环境:chrome浏览器
- 有h5文档申明:<!DOCTYPE html> Standard 模式下
document.body.scrollTop 始终为0
document.documentElement.scrollTop 获取正确
window.pageYOffset 获取正确 - 无文档申明
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-width1. heightdocument.querySelector('#out').clientHeight 340 300(h) + 20(p)*2 document.querySelector('#out').offsetHeight 360 300(h) + 20(p)*2 + 10(h)*2document.querySelector('#out').scrollHeight 540 500(h) + 20(p)*2 2. widthdocument.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肯定100pxdocument.querySelector('#out').clientTop 10 边框10document.querySelector('#out').offsetTop 100 margin 100document.querySelector('#out').scrollTop 100 滚动 100document.querySelector('#inner').clientTop 0 0document.querySelector('#inner').offsetTop 130 100 + 20 + 10document.querySelector('#inner').scrollTop 0 无滚动3.left 向下滚动inner肯定100pxdocument.querySelector('#out').clientLeft 10 边框10document.querySelector('#out').offsetLeft 0 document.querySelector('#out').scrollLeft 0
总结
- clientHeight 元素高度(不含boder)
- offsetHeight 元素高度(含boder)
- scrollHeight 滚动元素总高度
- scrollTop 滚动高度(暗藏局部)
- clientTop 上边框高度
- offsetTop 绝对于offsetParent的高度。offsetParent:间隔元素最近的一个具备定位的祖宗元素(relative,absolute,fixed),若祖宗都不符合条件,offsetParent为body。
- 当dom元素为doument.body或者document.documentElement时,clientHeight 等于屏幕高度。