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

前端 未结 27 4436
闹比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条回答
  •  梦毁少年i
    2020-11-21 05:29

    How about something like this, by passing ID of the element and it will return the left or top, we can also combine them:

    1) find left

    function findLeft(element) {
      var rec = document.getElementById(element).getBoundingClientRect();
      return rec.left + window.scrollX;
    } //call it like findLeft('#header');
    

    2) find top

    function findTop(element) {
      var rec = document.getElementById(element).getBoundingClientRect();
      return rec.top + window.scrollY;
    } //call it like findTop('#header');
    

    or 3) find left and top together

    function findTopLeft(element) {
      var rec = document.getElementById(element).getBoundingClientRect();
      return {top: rec.top + window.scrollY, left: rec.left + window.scrollX};
    } //call it like findTopLeft('#header');
    

提交回复
热议问题