js gets the position of the element relative to the page (viewable window), regardless of the page scrolling

Sometimes, when we are dealing with node rotation, the angle of rotation is calculated from the current clicked position and the center point of the node being rotated. The clicked position is relative to the visible window, so the center point of the rotated node must be relative to the visible window (otherwise when the scroll bar appears), otherwise there will be many problems in the calculation result.

Code:

// 获取元素相对于页面文档的位置----------------------------------------------
function getElementPos(el) {
    if(el.parentNode === null || el.style.display == 'none') {  return false;}     
    var parent = null;
    var pos = [];
    var box;
    if(el.getBoundingClientRect){     //IE
        box = el.getBoundingClientRect();
        var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
        var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
        return {x:box.left + scrollLeft, y:box.top + scrollTop};
     
    }else{ 
        pos = [el.offsetLeft, el.offsetTop]; 
        parent = el.offsetParent;    
        if (parent != el) {
            while (parent) { 
                pos[0] += parent.offsetLeft;
                pos[1] += parent.offsetTop;
                parent = parent.offsetParent;
            } 
        }  
    }  
    return {x:pos[0], y:pos[1]};
}   

Guess you like

Origin blog.csdn.net/qq_42740797/article/details/123121608