Created
February 25, 2017 15:01
-
-
Save tmslnz/9fc36105da7d3b09c1f3308d93de5573 to your computer and use it in GitHub Desktop.
Get HTMLElement offset relative to offsetParent, minus transforms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getOffset (node) { | |
var doc = node.ownerDocument; | |
var docElem = doc.documentElement; | |
var win = doc.defaultView; | |
var rect; | |
var result; | |
try { | |
rect = node.getBoundingClientRect(); | |
} catch (e) { | |
return { left: 0, top: 0 }; | |
} | |
var matrixString = window.getComputedStyle(node).transform; // can be "none" | |
var matrix = getCSSMatrix(matrixString); | |
result = { | |
left: rect.left + win.pageXOffset - docElem.clientLeft, | |
top: rect.top + win.pageYOffset - docElem.clientTop | |
}; | |
if (matrix.length) { | |
result.left -= matrix[4]; | |
result.top -= matrix[5]; | |
} | |
return result; | |
} | |
function getCSSMatrix (computedStyle) { | |
var values = computedStyle.split(/\w+\(|\);?/); | |
if (!values[1] || !values[1].length) { | |
return []; | |
} | |
return values[1].split(/,\s?/g).map(function (str) { return parseInt(str, 10) }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment