550 B
550 B
title, tags
| title | tags |
|---|---|
| getVerticalOffset | browser,beginner |
Finds the distance from a given element to the top of the document.
- Use a
whileloop andHTMLElement.offsetParentto move up the offset parents of the given element. - Add
HTMLElement.offsetTopfor each element and return the result.
const getVerticalOffset = el => {
let offset = el.offsetTop,
_el = el;
while (_el.offsetParent) {
_el = _el.offsetParent;
offset += _el.offsetTop;
}
return offset;
};
getVerticalOffset('.my-element'); // 120