二、元素的位置和距离

二、元素的位置和距离

2.1 定位父元素 offsetParent

  • 子绝父相中的父

  • 该元素不一定是父节点中的parentNode

dom结构:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>标题</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
position: relative;
width: 500px;
height: 500px;
margin: 0 auto;
background-color: red;
}
#box1 {
width: 250px;
height: 250px;
background-color: blue;
margin: 0 auto;
}
#box2 {
position: absolute;
width: 200px;
height: 200px;
left: 100px;
top: 100px;
background-color: orange;
}
</style>
</head>

<body>
<div id="box">
<div id="box1">
<div id="box2"></div>
</div>
</div>
<!-- 此时box2是相对于box进行定位的,在节点关系中box2的parentNode却是box1 -->
</body>

</html>

此时box2相对于box进行定位

如何通过box2得到定位父元素呢?

console.log(box2.offsetParent);

1
2
3
4
5
6
7
8
9
<script>
// 获取元素
var box = document.getElementById("box");
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");

// 通过box2获取自身的定位父元素
console.log(box2.offsetParent);
</script>

结果:

UMKrCQ.png

2.2 定位值 offsetLeft 和offsetTop

  • 元素的定位值也是经常要获取的值,所以dom也提供了相应的属性来获取

  • 快速获取元素的定位值的方式:

    • 距离自己定位父元素的左边距离:offsetLeft

    • 距离自己定位父元素的上边距离:offsetTop

1
2
3
// 获取box2的定位值
console.log("距离自己定位父元素的左边距离是:" + box2.offsetLeft); // 距离自己定位父元素的左边距离
console.log("距离自己定位父元素的上边距离是:" + box2.offsetTop); // 距离自己定位父元素的上边距离

UMKhUU.png

该属性存在兼容性问题:

  • 在高级浏览器中:是从子元素的边框外到父元素的边框内

  • 在IE中:是从子元素的边框外到父元素的边框外 也就是说多算了一条父元素的边框

在IE中输出定位值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#box {
position: relative;
width: 500px;
height: 500px;
margin: 0 auto;
background-color: red;
border: 5px solid #000;
}
#box1 {
width: 250px;
height: 250px;
background-color: blue;
margin: 0 auto;
}
#box2 {
position: absolute;
width: 200px;
height: 200px;
left: 100px;
top: 100px;
background-color: orange;
border: 5px solid #000;
}

UMKbK1.png

2.3 jquery中的定位值

使用方式:

$(dom).position()

返回值是一个对像

对象中包含left,就是dom的定位left值;同时包含top,就是dom的定位top值

执行代码:

1
2
3
// 获取box2的定位值
var $box2_position = $("#box2").position();
console.log($box2_position);

输出结果:

UMM3ZV.png

点击查看

本文标题:二、元素的位置和距离

文章作者:Mango

发布时间:2020年07月13日 - 22:35:42

最后更新:2020年07月14日 - 13:27:10

原始链接:https://mango185.github.io/post/8739b3ef.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------