-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoffsetParent.html
74 lines (66 loc) · 2.29 KB
/
offsetParent.html
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>offsetParent</title>
</head>
<style>
html { margin: 20px; padding: 10px;}
body { margin: 10px; }
#blue { height: 100px; width: 100px; background-color: blue; border: 10px solid gray; padding: 25px; margin: 25px; }
#red { height: 50px; width: 50px; background-color: red; border: 10px solid gray; }
#green { height: 100px; width: 100px; background-color: green; border: 10px solid gray; padding: 25px; margin: 25px; position: relative; }
#yellow { height: 50px; width: 50px; background-color: yellow; border: 10px solid gray; padding: 30px; margin: 20px;}
#body {
border: 20px solid gray;
margin: 10px;
padding: 40px;
height: 350px;
width: 500px;
position: relative;
}
#mdiv {
width: 400px;
height: 200px;
padding: 20px;
margin: 10px;
background-color: #F60;
border: 20px solid gray;
}
</style>
<body>
<div id="blue">
<div id="red"></div>
</div>
<div id="green">
<div id="yellow"></div>
</div>
<div id="body">
<div id="mdiv"></div>
</div>
<script>
// offsetParent 如何确定?
// 最近的不为 static 的祖先元素。
// 如果查询过程中未 table、th、td,那么即使定位值是 static,它将成为 offsetParent 的值。
// 如果没有已定位的父级元素,那么会以 html 为标准进行计算
// 偏移是根据 offsetParent 的内容区域来算的
// 注意垂直方向上的 margin 会合并,可以用 bfc 或 IE 下 haslayout 来阻止
let red = document.getElementById('red')
console.log(red.offsetParent) // body
console.log(red.offsetLeft) // margin25+border10+padding25+bodymargin10
console.log(red.offsetTop) // margin25+border10+padding25
console.log(red.clientLeft) // 10 就是边框
console.log(red.clientTop) // 10 就是边框
let yellow = document.getElementById('yellow')
console.log(yellow.offsetParent) // #green
console.log(yellow.offsetLeft) // padding25
console.log(yellow.offsetTop) // padding25
console.log(yellow.clientLeft) // 10 就是边框
console.log(yellow.clientTop) // 10 就是边框
let mdiv = document.getElementById('mdiv')
console.log(mdiv.offsetParent) // #body
console.log(mdiv.offsetLeft) // padding25
console.log(mdiv.offsetTop) // padding25
</script>
</body>
</html>