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

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

    The cleanest approach I have found is a simplified version of the technique used by jQuery's offset. Similar to some of the other answers it starts with getBoundingClientRect; it then uses the window and the documentElement to adjust for scroll position as well as things like the margin on the body (often the default).

    var rect = el.getBoundingClientRect();
    var docEl = document.documentElement;
    
    var rectTop = rect.top + window.pageYOffset - docEl.clientTop;
    var rectLeft = rect.left + window.pageXOffset - docEl.clientLeft;
    

    var els = document.getElementsByTagName("div");
    var docEl = document.documentElement;
    
    for (var i = 0; i < els.length; i++) {
    
      var rect = els[i].getBoundingClientRect();
    
      var rectTop = rect.top + window.pageYOffset - docEl.clientTop;
      var rectLeft = rect.left + window.pageXOffset - docEl.clientLeft;
    
      els[i].innerHTML = "" + rectLeft + ", " + rectTop + "";
    }
    div {
      width: 100px;
      height: 100px;
      background-color: red;
      border: 1px solid black;
    }
    #rel {
      position: relative;
      left: 10px;
      top: 10px;
    }
    #abs {
      position: absolute;
      top: 250px;
      left: 250px;
    }

提交回复
热议问题