How does js get the position of an element on the screen?

is the distance of the element relative to the left and top edges of the screen,

whether or not this element is detached from the document stream or the page is scrolling,

how can I get it correctly?

there is something wrong with the offsetTop and offsetLeft I use now. It will not work if the page is scrolled


call dom.getBoundingClientRect () to get.


// IE
//  
function intval(v) {
    v = parseInt(v);
    return isNaN(v) ? 0 : v;
}

function getPos(e) {
    // left and top value
    var left = 0;
    var top = 0;

    // offsetParent,html/body,.
    while (e.offsetParent) {
        // 
        left += e.offsetLeft + (e.currentStyle ? intval(e.currentStyle.borderLeftWidth) : 0);
        top += e.offsetTop + (e.currentStyle ? intval(e.currentStyle.borderTopWidth) : 0);

        // body
        e = e.offsetParent;
    }

    left += e.offsetLeft + (e.currentStyle ? intval(e.currentStyle.borderLeftWidth) : 0);
    top += e.offsetTop + (e.currentStyle ? intval(e.currentStyle.borderTopWidth) : 0);

    return {
        x: left,
        y: top
    };
}

document.addEventListener('mousemove', function(e) {
    // DOM
    console.log(getPos(document.querySelector('.footer')))
})
Menu