元素在网页或视口上位置的相关问题求解

1、求元素在整张网页的高度和宽度
可从document.documentElement(即<html>元素)或<body>元素上读取。

//网页总高度
Document.documentElement.offsetHeight
Document.documentElement.scrollHeight
Document.body.offsetHeight
Document.body.scrollHeight

由于html和body的宽度可能设置的不一样,因此从body上取会更保险些。。。

2、求元素在视口的高度和宽度

Window.innerHeight//包括滚动条
Document.documentElement.clientHeight//不包括滚动条

3、求某个网页元素在视口上的坐标,使用element.getBoundingClientRect方法获取

//网页元素在视口上的横坐标
Element.getBoundingClientRect().left
//网页元素在视口上的纵坐标
Element.getBoundingClientRect().top

4、求某个网页元素在网页上的坐标,使用视口坐标加上网页滚动距离。

//元素在网页上的横坐标
Element.getBoundingClientRect().left+document.documentElement.scrollLeft
//元素在网页上的横坐标
Element.getBoundingClientRect().top+document.documentElement.scrollTop

5、网页元素本身的高度和宽度
1)、通过offsetHeight和offsetWidth(width、padding和border)
2)、通过clientHeight和clientWidth(width和padding)

原文地址:https://www.cnblogs.com/MelodysBlog/p/10449469.html