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

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

    This worked for me (modified from highest voted answer):

    function getOffset(el) {
      const rect = el.getBoundingClientRect();
      return {
        left: rect.left + window.scrollX,
        top: rect.top + window.scrollY
      };
    }
    

    Using this we can call

    getOffset(element).left
    

    or

    getOffset(element).top
    

提交回复
热议问题