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

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

    You can add two properties to Element.prototype to get the top/left of any element.

    Object.defineProperty( Element.prototype, 'documentOffsetTop', {
        get: function () { 
            return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
        }
    } );
    
    Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
        get: function () { 
            return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 );
        }
    } );
    

    This is called like this:

    var x = document.getElementById( 'myDiv' ).documentOffsetLeft;
    

    Here's a demo comparing the results to jQuery's offset().top and .left: http://jsfiddle.net/ThinkingStiff/3G7EZ/

提交回复
热议问题