当前位置:网站首页>Get the exact offset of the element

Get the exact offset of the element

2022-07-07 22:21:00 Belden wind

adopt getBoundingClientRect obtain ( recommend )

const getOffset = (element: HTMLElement) => {
    
    const elemRect = element.getBoundingClientRect();
    const offsetY = elemRect.top + window.scrollY;
    const offsetX = elemRect.left + window.scrollX;
    return {
    
        left: offsetX,
        top: offsetY,
    };
};

adopt offsetParent obtain ,( If the element has translate(xx,xx), It will fail

const getOffset = (
    element: HTMLElement,
    type: 'offsetTop' | 'offsetLeft'
): number => {
    
    let actualOffset = element[type];
    let current = element.offsetParent as HTMLElement;

    while (current !== null) {
    
        actualOffset += current[type];
        current = current.offsetParent as HTMLElement;
    }
    return actualOffset;
};

Reference documents

原网站

版权声明
本文为[Belden wind]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130607022292.html