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

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

    You might be better served by using a JavaScript framework, that has functions to return such information (and so much more!) in a browser-independant fashion. Here are a few:

    • Prototype
    • jQuery
    • MooTools
    • YUI (yahoo)

    With these frameworks, you could do something like: $('id-of-img').top to get the y-pixel coordinate of the image.

    0 讨论(0)
  • 2020-11-21 05:27

    I've taken @meouw's answer, added in the clientLeft that allows for the border, and then created three versions:

    getAbsoluteOffsetFromBody - similar to @meouw's, this gets the absolute position relative to the body or html element of the document (depending on quirks mode)

    getAbsoluteOffsetFromGivenElement - returns the absolute position relative to the given element (relativeEl). Note that the given element must contain the element el, or this will behave the same as getAbsoluteOffsetFromBody. This is useful if you have two elements contained within another (known) element (optionally several nodes up the node tree) and want to make them the same position.

    getAbsoluteOffsetFromRelative - returns the absolute position relative to the first parent element with position: relative. This is similar to getAbsoluteOffsetFromGivenElement, for the same reason but will only go as far as the first matching element.

    getAbsoluteOffsetFromBody = function( el )
    {   // finds the offset of el from the body or html element
        var _x = 0;
        var _y = 0;
        while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
        {
            _x += el.offsetLeft - el.scrollLeft + el.clientLeft;
            _y += el.offsetTop - el.scrollTop + el.clientTop;
            el = el.offsetParent;
        }
        return { top: _y, left: _x };
    }
    
    getAbsoluteOffsetFromGivenElement = function( el, relativeEl )
    {   // finds the offset of el from relativeEl
        var _x = 0;
        var _y = 0;
        while( el && el != relativeEl && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
        {
            _x += el.offsetLeft - el.scrollLeft + el.clientLeft;
            _y += el.offsetTop - el.scrollTop + el.clientTop;
            el = el.offsetParent;
        }
        return { top: _y, left: _x };
    }
    
    getAbsoluteOffsetFromRelative = function( el )
    {   // finds the offset of el from the first parent with position: relative
        var _x = 0;
        var _y = 0;
        while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
        {
            _x += el.offsetLeft - el.scrollLeft + el.clientLeft;
            _y += el.offsetTop - el.scrollTop + el.clientTop;
            el = el.offsetParent;
            if (el != null)
            {
                if (getComputedStyle !== 'undefined')
                    valString = getComputedStyle(el, null).getPropertyValue('position');
                else
                    valString = el.currentStyle['position'];
                if (valString === "relative")
                    el = null;
            }
        }
        return { top: _y, left: _x };
    }
    

    If you are still having problems, particularly relating to scrolling, you could try looking at http://www.greywyvern.com/?post=331 - I noticed at least one piece of questionable code in getStyle which should be fine assuming browsers behave, but haven't tested the rest at all.

    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2020-11-21 05:31

    Get position of div in respect to left and Top

      var elm = $('#div_id');  //get the div
      var posY_top = elm.offset().top;  //get the position from top
      var posX_left = elm.offset().left; //get the position from left 
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题