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

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

提交回复
热议问题