UNPKG

925 BJavaScriptView Raw
1export default function calculateDimension(el, axis, borderBox = false, withMargin = false) {
2 if (!el) {
3 return 0;
4 }
5
6 const axisStart = axis === 'width' ? 'Left' : 'Top';
7 const axisEnd = axis === 'width' ? 'Right' : 'Bottom';
8
9 // Only read styles if we need to
10 const style = (!borderBox || withMargin) ? window.getComputedStyle(el) : null;
11
12 // Offset includes border and padding
13 const { offsetWidth, offsetHeight } = el;
14 let size = axis === 'width' ? offsetWidth : offsetHeight;
15
16 // Get the inner size
17 if (!borderBox) {
18 size -= (
19 parseFloat(style[`padding${axisStart}`])
20 + parseFloat(style[`padding${axisEnd}`])
21 + parseFloat(style[`border${axisStart}Width`])
22 + parseFloat(style[`border${axisEnd}Width`])
23 );
24 }
25
26 // Apply margin
27 if (withMargin) {
28 size += (parseFloat(style[`margin${axisStart}`]) + parseFloat(style[`margin${axisEnd}`]));
29 }
30
31 return size;
32}