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

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

    Just thought I'd throw this out there as well.
    I haven't been able to test it in older browsers, but it works in the latest of the top 3. :)

    Element.prototype.getOffsetTop = function() {
        return ( this.parentElement )? this.offsetTop + this.parentElement.getOffsetTop(): this.offsetTop;
    };
    Element.prototype.getOffsetLeft = function() {
        return ( this.parentElement )? this.offsetLeft + this.parentElement.getOffsetLeft(): this.offsetLeft;
    };
    Element.prototype.getOffset = function() {
        return {'left':this.getOffsetLeft(),'top':this.getOffsetTop()};
    };
    

提交回复
热议问题