Created
July 2, 2017 08:19
-
-
Save weihanglo/b20990b666e7a0bb7119bfe08787892a to your computer and use it in GitHub Desktop.
Get real element offset with an offsetParent referencing element
This file contains 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
/** | |
* Get real element offset with an offsetParent referencing element | |
* | |
* `getBoundingClientRect` return values is not correct under CSS multi-column | |
* layout, so we recursively get `offsetLeft`/`offsetTop` instead. | |
* @param {HTMLElement} el - element of interest | |
* @param {HTMLElement} stopEl - one of the offsetParent as a reference | |
* @return {object} object wth top and left offset | |
*/ | |
export function getClientOffset (el, stopEl) { | |
/// tail-called optimize | |
function getOffset(el, stopEl, left = 0, top = 0) { | |
if (el === stopEl) { | |
return { left, top } | |
} | |
return getOffset( | |
el.offsetParent, | |
stopEl, | |
left + el.offsetLeft, | |
top + el.offsetTop | |
) | |
} | |
return getOffset(el, stopEl) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment