forked from danbeam/outer-dimensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
outer-dimensions.js
66 lines (57 loc) · 1.5 KB
/
outer-dimensions.js
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
(function() {
// Note: box-sizing: border-box; doesn't seem to affect results as
// offset{Height,Width} already accounts for this.
/**
* @param {!HTMLElement} el
* @param {!CSSStyleDeclaration} style
*/
function getHeight(el, style) {
return el.offsetHeight
// These are accounted for by offsetWidth.
// + parseFloat(style.borderTopWidth)
// + parseFloat(style.borderBottomWidth)
+ parseFloat(style.marginTop)
+ parseFloat(style.marginBottom);
}
/**
* @param {!HTMLElement} el
* @param {!CSSStyleDeclaration} style
*/
function getWidth(el, style) {
return el.offsetWidth
// + parseFloat(style.borderLeftWidth)
// + parseFloat(style.borderRightWidth)
+ parseFloat(style.marginLeft)
+ parseFloat(style.marginRight);
}
/**
* @param {!HTMLElement} el
* @return {boolean} Whether |el| can have valid dimensions.
*/
function hasDimensions(el) {
return !!el.parentNode;
}
Object.defineProperties(HTMLElement.prototype, {
outerDimensions: {
get: function() {
if (!hasDimensions(this))
return {height: 0, width: 0};
var styles = getComputedStyle(this);
return {
height: getHeight(this, styles),
width: getWidth(this, styles),
};
},
},
outerHeight: {
get: function() {
return hasDimensions(this) ? getHeight(this, getComputedStyle(this)) : 0;
},
},
outerWidth: {
get: function() {
return hasDimensions(this) ? getWidth(this, getComputedStyle(this)) : 0;
},
},
});
})();