问题引入:面试的时候被问到如果我们已经获取dom结构,怎么获取它的位置
我:瞎扯一通后(原生的api实在不太记得)
相信读完本篇文章会有一个答案,答案在最后一部分,想直接知道答案,可以直接跳到最后一部分。
前言
- 先约定,本文盒子用的标准盒模型
- 本文就下面这个盒子(inner)进行讨论,盒子样式和样式如下
offset系列
offsetParent
只读属性。返回一个最近的(指包含层级上的最近)包含该元素的定位元素或者最近的table,td,th,body元素。当元素display设置为none是,offsetParent返回null
offsetTop、offsetLeft
只读属性。
offsetTop: 它返回当前元素相对于其 offsetParent
元素的顶部内边距的距离
offsetLeft: 元素到offsetParent左侧的距离
// offsetTop 下图黄色部分
// 本示例的body的内边距0,
offsetTop = inner盒子顶部边框线到body顶部内边距的距离
// offsetLeft 示图绿色部分
offsetLeft = inner盒子左侧边框线到body左侧内边距的距离
offsetWidth、offsetHeight
只读属性,返回一个元素的布局宽(高)度
offsetWidth:width + 左右paddind + 左右border
offsetHeight:height + 上下paddin + 上下border
分析offsetHeight 和 offsetWidth
// 绿色 offsetwidth
offsetWidth = border-left-width + padding-left + width + padding-right + border-right-width
220 = 40 + 40 + 100 + 20 + 20
// 黄色 offseHeight
offsetHeight = border-top-width + padding-top + height + padding-bottom + border-bottom-width
280 = 10 + 10 + 200 + 30 + 30
offsetX、offsetY
event.offsetX相对容器的水平坐标
event.offsetY相对容器的垂直坐标
client系列
clientWidth、clientHeight
表示元素的内部宽(高)度,以像素计。包括内边距padding,不包括边框border、外边距margin和垂直(横向)滚动条 内联元素以及没有CSS样式的元素的该属性值为0. 表达式:
clientWidth = width + 左右padding
clientHeight = height + 上下padding
// clientWidth 绿色
clientWidth = 100 + 20 + 40 = 160
// clientHeight 黄色
clientHeight = 200 + 10 + 30 = 240
clientTop、clientLeft
clientTop: 一个元素顶部边框的宽度,不包括顶部外边距和内边距,该属性只读。 clientLeft: 一个元素左侧部边框的宽度,不包括顶部外边距和内边距,该属性只读。
clientWidth = border-top-width // 10
clientHeight = border-left-width // 40
clientX、clientY
只读属性
MouseEvent.clientX
:事件发生时的应用客户端区域的水平坐标(与页面坐标不同)。无论页面是否水平滑动,当我们点击客户端区域的左上角是,鼠标时间的clientX值都为0。
MouseEvent.clientY
同理
示例
<!DOCTYPE html>
<html>
<head>
<title>clientX/clientY example</title>
<script>
function showCoords(event){
alert(
"clientX value: " + event.clientX + "\n" +
"clientY value: " + event.clientY + "\n"
);
}
</script>
</head>
<body onmousedown="showCoords(event)">
<p>To display the mouse coordinates click anywhere on the page.</p>
</body>
</html>
scroll系列
scrollWidth、scrollHeight
只读属性。是元素的内容宽度的一种毒狼,包括由于overflow溢出而在屏幕上不可见的内容 scrollWidth值等于元素在不使用水平滚动条的情况下适合视口中的所有内容所需的最小 宽度。宽度度量的测量方式clientWidth相同,包含元素的内边距
scrollTop、scrollLeft
Element.scrollTop
属性可以获取或设置一个元素的内容垂直滚动的像素数。
当元素不可滚动的时候scrollTop
的值是0,
当元素可以滚动,则表示元素顶部到可视区域的距离
例如:当一个元素的内容往上滚动了10px,则scrollTop的值就为 0 - 10 = -10
getBoundingClientRect
Element.getBoundingClientRect
方法返回元素的大小以及相对视口的位置
尺寸就是为offsetWidth/offsetHeight的值
图片来自MDN