获取元素准确的offset

  • Post author:
  • Post category:其他




通过getBoundingClientRect获取(推荐)

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,
    };
};




通过offsetParent获取,(如果元素有translate(xx,xx),将会失效

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;
};


参考文档



版权声明:本文为qq_33051709原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。