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

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

    The libraries go to some lengths to get accurate offsets for an element.
    here's a simple function that does the job in every circumstances that I've tried.

    function getOffset( 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 };
    }
    var x = getOffset( document.getElementById('yourElId') ).left; 
    

提交回复
热议问题