Get the position of an element without taking into account any transformation in the element and up to the DOM tree:
var el = element, offsetLeft = 0, offsetTop = 0; do{ offsetLeft += el.offsetLeft; offsetTop += el.offsetTop; el = el.offsetParent; } while( el );
Get the position of an element without considering the transformation applied to it, but storing any transformation in the DOM tree.
To do this, you can try to return the conversion.
You must first set transform-origin to 0,0,0 and surround yourself with your transformation (scale, rotation) of width translate(50%,50%) ... translate(-50%, -50%) . Here is an example
change this:
transform: scale(2) rotate(45deg) translate(20px); transform-origin: 50% 50%; //default value
in
transform: translate(50%, 50%) scale(2) rotate(45deg) translate(-50%,-50%) translate(20px); transform-origin: 0 0 0;
We need to do this because the matrix returned by getComputedStyle () does not include material created using the origin transformation. I do not know why.
Then you can use this code:
function parseTransform(transform){ //add sanity check return transform.split(/\(|,|\)/).slice(1,-1).map( function(v){ return parseFloat(v); }); } function convertCoord(transformArr, x, y, z){ //add sanity checks and default values if( transformArr.length == 6 ){ //2D matrix //need some math to apply inverse of matrix var t = transformArr, det = t[0]*t[3] - t[1]*t[2]; return { x: ( x*t[3] - y*t[2] + t[2]*t[5] - t[4]*t[3] )/det, y: ( -x*t[1] + y*t[0] + t[4]*t[1] - t[0]*t[5] )/det } } else /*if (transformArr.length > 6)*/{ //3D matrix //haven't done the calculation to apply inverse of 4x4 matrix } } var elRect = element.getBoundingClientRect(), st = window.getComputedStyle(element), topLeft_pos = convertCoord( parseTransform( st.transform ), elRect.left, elRect.top, st.perspective );
I will not explain the mathematical part, because I think this is beyond the scope of this publication. Could still explain it somewhere else (maybe another question?).