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

前端 未结 27 3783
闹比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:50

    /**
     *
     * @param {HTMLElement} el
     * @return {{top: number, left: number}}
     */
    function getDocumentOffsetPosition(el) {
        var position = {
            top: el.offsetTop,
            left: el.offsetLeft
        };
        if (el.offsetParent) {
            var parentPosition = getDocumentOffsetPosition(el.offsetParent);
            position.top += parentPosition.top;
            position.left += parentPosition.left;
        }
        return position;
    }
    

    Thank ThinkingStiff for the answer, this is only another version.

提交回复
热议问题