Skip to content

Instantly share code, notes, and snippets.

@weihanglo
Created July 2, 2017 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weihanglo/b20990b666e7a0bb7119bfe08787892a to your computer and use it in GitHub Desktop.
Save weihanglo/b20990b666e7a0bb7119bfe08787892a to your computer and use it in GitHub Desktop.
Get real element offset with an offsetParent referencing element
/**
* 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