js 获取页面/元素的宽、高、距离

Document对象是每个DOM树的根,但是它并不代表树中的一个HTML元素,
document.documentElement属性引用了作为文档根元素的html标记,

整个文档的宽度:document.documentElement.scrollWidth
整个文档的高度:document.documentElement.scrollHeight
整个文档的可见宽度:document.documentElement.clientWidth (不包含边框的宽)
整个文档的可见高度:document.documentElement.clientHeight (不包含边框的宽)
整个文档的可见宽度:document.documentElement.offsetWidth (包括边线的宽)
整个文档的可见高度:document.documentElement.offsetHeight (包括边线的宽)

document.body属性引用了body标记
body正文全文宽:document.body.scrollWidth
body正文全文高:document.body.scrollHeight
body可见区域宽:document.body.clientWidth (不包括边线的宽) width+左右padding
body可见区域高:document.body.clientHeight (不包括边线的高) height + 上下padding
body可见区域宽:document.body.offsetWidth (包括边线的宽)
body可见区域高:document.body.offsetHeight (包括边线的高)

var cWidth = document.body.clientWidth || document.documentElement.clientWidth;//页面可视区域宽度
var iWidth = window.innerWidth;//浏览器窗口大小
console.log(iWidth - cWidth);//打印滚动条宽度

在不同的浏览器中,有些能识别document.body.scrollTop,有些能识别document.documentElement.scrollTop
网页被卷去的高:document.body.scrollTop || document.documentElement.scrollTop
网页被卷去的左:document.body.scrollLeft || document.documentElement.scrollLeft

body和documentElement的区别
document.body.scrollHeight == document.body.offsetHeight == document.body.clientHeight
document.documentElement.scrollHeight == document.documentElement.offsetHeight

document.body.scrollHeight ≠ document.documentElement.scrollHeight
document.body.offsetHeight ≠ document.documentElement.offsetHeight
document.body.clientHeight ≠ document.documentElement.clientHeight

网页正文部分上:window.screenTop
网页正文部分左:window.screenLeft
屏幕分辨率的高:window.screen.height
屏幕分辨率的宽:window.screen.width
屏幕可用工作区高度:window.screen.availHeight
屏幕可用工作区宽度:window.screen.availWidth

获取可视区窗口宽度:window.innerWidth
获取可视区窗口高度:window.innerHeight

clientWidth = 元素width + 元素左右padding
clientHeight = 元素height + 元素上下padding
clientLeft 属性返回元素左边框的宽度(border)。此属性不包括元素的左margin或左padding 。此属性是只读的。
提示:您还可以使用style.borderLeftWidth属性返回元素左边框的宽度。
clientTop属性返回元素顶部边框的宽度。此属性不包括元素的顶部填充或上边距。此属性是只读的。
提示:您还可以使用style.borderTopWidth属性返回元素顶部边框的宽度。

offsetWidth = 元素width + 元素左右padding + 元素左右boder = clientWidth + 元素左右boder
offsetHeight = 元素height + 元素上下padding + 元素上下boder = clientHeight + 元素上下boder
offsetLeft = 当前元素 marginLeft + 最近的已定位父级(offsetParent) paddingLeft
offsetTop = 当前元素 marginTop + 最近的已定位父级(offsetParent) paddingTop
如果父级都没有定位,offsetLeft,offsetTop 是当前元素 分别到 body 顶部 和 左边 的距离。

 

posted @ 2022-12-13 14:23  柔和的天空  阅读(2894)  评论(0编辑  收藏  举报