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

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

提交回复
热议问题