-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (61 loc) · 1.76 KB
/
index.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
67
68
69
70
71
72
73
74
75
76
77
;(function() {
var units = {
ew: function(context) {
var width = context.getBoundingClientRect().width;
return width / 100;
},
eh: function(context) {
var height = context.getBoundingClientRect().height;
return height / 100;
},
lh: function(context) {
var element = document.createElement('div');
element.innerHTML = 'spatio';
Object.assign(element.style, {
visibility: 'hidden',
position: 'fixed'
});
context.appendChild(element);
return spatio('100eh', 'px', element);
},
ls: function(context) {
return spatio(2.998e10 + 'cm', 'px');
}
};
function convert(expression, context) {
expression = Object.keys(units).reduce(
function(expression, key) {
return expression.replace(
new RegExp('([0-9]*(?:\\.[0-9]*)?)' + key, 'g'),
function(match, value) { return units[key](context) * Number(value) + 'px'; }
)
}
, expression);
var element = document.createElement('div');
Object.assign(element.style, {
width: expression,
height: '1px',
visibility: 'hidden',
position: 'fixed'
});
context.appendChild(element);
var elementRect = element.getBoundingClientRect()
element.remove();
return elementRect.width / elementRect.height;
}
function spatio(expression, unit, context) {
unit = unit || 'px';
context = context || document.body;
var from = convert(expression, context);
var to = convert('1' + unit, context);
return from / to;
}
spatio.addUnits = function(newUnits) {
units = Object.assign({}, units, newUnits);
};
if (typeof module !== 'undefined') {
module.exports = spatio;
} else {
self.spatio = spatio;
}
})();