-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheight-matcher.js
113 lines (94 loc) · 2.5 KB
/
height-matcher.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
(function (getBoundingClientRect) {
/**
* Gets an element's pixel height including borders and padding,
* excluding margin
*/
function getHeight(el) {
var _ = el[getBoundingClientRect]();
return _.bottom - _.top;
}
/*
*
*/
function getTop(el) {
return el[getBoundingClientRect]().top;
}
/*
* Sets the height of an element so that its bounding box (offset height) will
* be the height given, regardless of borders, padding, box-sizing or units of
* measurement
*/
function setHeight(el, height) {
var style = el.style
var actualHeight;
// set the height naively
style._height = style.height;
style.height = height + 'px';
// test the element's new height
actualHeight = getHeight(el);
// if it isn't correct, adjust
if (actualHeight !== height) {
style.height = (height + height - actualHeight) + 'px';
}
}
/*
* Removes any previously applied heights to an element
*/
function restoreHeight(el) {
el.style.height = el.style._height || '';
el.style._height = null;
}
/*
* Batches elements up into groups that lie on the same row as each other
*/
function getRows(elems) {
var rows = [];
var elem;
var i;
for (i = 0; i < elems.length; i++) {
elem = elems[i];
// if this is the first element, or the top of this element isn't in line
// with the previous element, start a new row
if (!rows.length || Math.floor(Math.abs(getTop(elem) - getTop(elems[i-1]))) > 1) {
rows.push([elem]);
}
// else, add to the end of the current row
else {
rows[rows.length - 1].push(elem);
}
}
return rows;
}
/*
*
*/
function matchHeight(elems, all) {
var rows = all ? [elems] : getRows(elems);
var maxHeight;
var i, j;
matchHeight.restore(elems);
// in each row
for (i = 0; i < rows.length; i++) {
maxHeight = 0;
// find the tallest element
for (j = 0; j < rows[i].length; j++) {
maxHeight = Math.max(getHeight(rows[i][j]), maxHeight);
}
// adjust all other elemets to match
for (j = 0; j < rows[i].length; j++) {
setHeight(rows[i][j], maxHeight);
}
}
}
/*
*
*/
matchHeight.restore = function (elems) {
var i;
for (i = 0; i < elems.length; i++) {
restoreHeight(elems[i]);
}
}
// expose the function
window.matchHeight = matchHeight;
})('getBoundingClientRect'); // improves compression