-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetBoundingClientRectExample.htm
More file actions
executable file
·91 lines (69 loc) · 2.91 KB
/
Copy pathGetBoundingClientRectExample.htm
File metadata and controls
executable file
·91 lines (69 loc) · 2.91 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<!DOCTYPE html>
<html>
<head>
<title>getBoundingClientRect() Example</title>
<script type="text/javascript">
function getElementLeft(element){
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null){
actualLeft += current.offsetLeft;
current = current.offsetParent;
}
return actualLeft;
}
function getElementTop(element){
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null){
actualTop += current. offsetTop;
current = current.offsetParent;
}
return actualTop;
}
function getBoundingClientRect(element){
var scrollTop = document.documentElement.scrollTop;
var scrollLeft = document.documentElement.scrollLeft;
if (element.getBoundingClientRect){
if (typeof arguments.callee.offset != "number"){
var temp = document.createElement("div");
temp.style.cssText = "position:absolute;left:0;top:0;";
document.body.appendChild(temp);
arguments.callee.offset = -temp.getBoundingClientRect().top - scrollTop;
document.body.removeChild(temp);
temp = null;
}
var rect = element.getBoundingClientRect();
var offset = arguments.callee.offset;
return {
left: rect.left + offset,
right: rect.right + offset,
top: rect.top + offset,
bottom: rect.bottom + offset
};
} else {
var actualLeft = getElementLeft(element);
var actualTop = getElementTop(element);
return {
left: actualLeft - scrollLeft,
right: actualLeft + element.offsetWidth - scrollLeft,
top: actualTop - scrollTop,
bottom: actualTop + element.offsetHeight - scrollTop
}
}
}
function getDimensions(){
var rect = getBoundingClientRect(document.getElementById("myDiv"));
alert("left: " + rect.left + "\nright: " + rect.right + "\ntop: " + rect.top + "\nbottom: " + rect.bottom);
}
</script>
</head>
<body style="padding: 10px; margin: 0">
<div style="margin: 20px">
<div style="padding: 20px">
<div id="myDiv" style="width: 100px; height: 50px; background-color: red; border: 1px solid black"></div>
</div>
</div>
<input type="button" value="Get Element Dimensions" onclick="getDimensions()" />
</body>
</html>