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

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

    Difference between small and little

    function getPosition( el ) {
        var x = 0;
        var y = 0;
        while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        x += el.offsetLeft - el.scrollLeft;
        y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
        }
        return { top: y, left: x };
    }
    

    Look a example coordinates: http://javascript.info/tutorial/coordinates

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

    To retrieve the position relative to the page efficiently, and without using a recursive function: (includes IE also)

    var element = document.getElementById('elementId'); //replace elementId with your element's Id.
    var rect = element.getBoundingClientRect();
    var elementLeft,elementTop; //x and y
    var scrollTop = document.documentElement.scrollTop?
                    document.documentElement.scrollTop:document.body.scrollTop;
    var scrollLeft = document.documentElement.scrollLeft?                   
                     document.documentElement.scrollLeft:document.body.scrollLeft;
    elementTop = rect.top+scrollTop;
    elementLeft = rect.left+scrollLeft;
    
    0 讨论(0)
提交回复
热议问题