Are you an LLM? You can read better optimized documentation at /vite-press/frontend/javascript/ElementPosition.md for this page in Markdown format
元素位置
scroll
scrollWidth 和 scrollHeight、scrollTop 和 scrollLeft
scrollWidth的实际宽度:获取指定标签内容层的真实宽度(可视区域宽度+被隐藏区域宽度)
js
scrollWidth = dom?.scrollWidth1
scrollHeight的实际高度:获取指定标签内容层的真实高度(可视区域高度+被隐藏区域高度)
js
scrollHeight = dom?.scrollHeight1
scrollTop:内容层顶部 到 可视区域顶部的距离。(被隐藏区域高度)
js
scrollTop = dom?.scrollTop1
scrollLeft:内容层左端 到 可视区域左端的距离。(被隐藏区域宽度)
js
scrollLeft = dom?.scrollLeft1
client
clientWidth 和 clientHeight、clientTop 和 clientLeft
clientWidth的实际宽度:width+ 左右padding。 (可视区域宽度)
js
clientWidth = dom?.clientWidth1
clientHeight的实际高度:height+ 上下padding。 (可视区域高度)
js
clientHeight = dom?.clientHeight1
clientTop:border.top(上边框的宽度)
js
clientTop = dom?.clientTop1
clientLeft:border.left(左边框的宽度)
js
clientLeft = dom?.clientLeft1
offset
offsetWidth 和 offsetHeight、offsetTop 和 offsetLeft
offsetWidth的实际宽度:width+ 左右padding+ 左右border
js
offsetWidth = dom?.offsetWidth1
offsetHeight的实际高度:height+ 上下padding+ 上下border
js
offsetHeight = dom?.offsetHeight1
offsetTop:当前元素 上边框外边缘 到最近的已定位父级(offsetParent) 上边框内边缘 的距离。如果父级都没有定位,则是到 body顶部 的距离
js
offsetTop = dom?.offsetTop1
offsetLeft:当前元素 左边框外边缘 到最近的已定位父级(offsetParent)左边框内边缘 的距离。如果父级都没有定位,则是到 body左边 的距离
js
offsetLeft = dom?.offsetLeft1
event
screen
screenX:返回当某个事件被触发时,鼠标指针相对于显示器的水平坐标。screenY:返回当某个事件被触发时,鼠标指针相对于显示器的垂直坐标。
js
evt?.screenX
evt?.screenY1
2
2
page
pageX:鼠标到文档左边的距离,包括滚动隐藏区域pageY:鼠标到文档顶部的距离,包括滚动隐藏区域
js
evt?.pageX
evt?.pageY1
2
2
offset
offsetX:鼠标到事件源左边框内侧的距离offsetY:鼠标到事件源上边框内侧的距离
js
evt?.offsetX
evt?.offsetY1
2
2
client
clientX:鼠标到文档左边的距离,不包括滚动隐藏区域clientY:鼠标到文档顶部的距离,不包括滚动隐藏区域
js
evt?.clientX
evt?.clientY1
2
2
应用
- 计算元素距离 浏览器左上角 的距离
ts
const getOffsetLeft = (dom: HTMLElement) => {
let offsetLeft = dom.offsetLeft
let parent = dom.offsetParent as (HTMLElement | null)
while (parent) {
offsetLeft += parent.offsetLeft
parent = parent.offsetParent as (HTMLElement | null)
}
return offsetLeft
}
const getOffsetTop = (dom: HTMLElement) => {
let offsetTop = dom.offsetTop
let parent = dom.offsetParent as (HTMLElement | null)
while (parent) {
offsetTop += parent.offsetTop
parent = parent.offsetParent as (HTMLElement | null)
}
return offsetTop
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19