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

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

    Since different browsers are rendering border, padding, margin and etc in different way. I wrote a little function to retrieve top and left positions of specific element in every root element that you want in precise dimension:

    function getTop(root, offset) {
        var rootRect = root.getBoundingClientRect();
        var offsetRect = offset.getBoundingClientRect();
        return offsetRect.top - rootRect.top;
    }
    

    For retrieve left position you must return:

        return offsetRect.left - rootRect.left;
    

提交回复
热议问题