43.获取元素位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<style>
*{
margin: 0;
padding: 0;
}
.father{
width: 200px;
height: 200px;
margin-top: 100px;
margin-left: 100px;
background: blue;
overflow: hidden;
/*position: relative;*/
}
.son{
width: 100px;
height: 100px;
margin-top: 100px;
margin-left: 100px;
background: red;
}
</style>

<div class="father">
<div class="son"></div>
</div>

let oSDiv = document.querySelector(".son");
oSDiv.onclick = function () {
console.log(oSDiv.offsetLeft);
console.log(oSDiv.offsetTop);
}
  • 没有定位时,输出两个200

  • 如果加上position: relative,输出100

  1. offsetLeft和offsetTop作用获取元素到第一个定位祖先元素之间的偏移位
    如果没有祖先元素是定位的, 那么就是获取到body的偏移位

left,top是定位的素材可以设置的属性