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

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

    After much research and testing this seems to work

    function getPosition(e) {
        var isNotFirefox = (navigator.userAgent.toLowerCase().indexOf('firefox') == -1);
        var x = 0, y = 0;
        while (e) {
            x += e.offsetLeft - e.scrollLeft + (isNotFirefox ? e.clientLeft : 0);
            y += e.offsetTop - e.scrollTop + (isNotFirefox ? e.clientTop : 0);
            e = e.offsetParent;
        }
        return { x: x + window.scrollX, y: y + window.scrollY };
    }
    

    see http://jsbin.com/xuvovalifo/edit?html,js,output

提交回复
热议问题