Retrieve the position (X,Y) of an HTML element relative to the browser window

前端 未结 27 4596
闹比i
闹比i 2020-11-21 04:59

I want to know how to get the X and Y position of HTML elements such as img and div in JavaScript relative to the browser window.

27条回答
  •  佛祖请我去吃肉
    2020-11-21 05:44

    To get the total offset of an element, you could recursively sum up all parent offsets:

    function getParentOffsets(el): number {
    if (el.offsetParent) {
        return el.offsetParent.offsetTop + getParentOffset(el.offsetParent);
    } else {
        return 0;
    }
    }
    

    with this utility function the total top offset of a dom element is:

    el.offsetTop + getParentOffsets(el);
    

提交回复
热议问题