Saber2pr's Blog

获取元素距离文档顶部的距离

export function getElementTop(elem: HTMLElement) {
  let elemTop = elem.offsetTop
  elem = elem.offsetParent as HTMLElement
  while (elem != null) {
    elemTop += elem.offsetTop
    elem = elem.offsetParent as HTMLElement
  }
  return elemTop
}

获取元素距离浏览器视口顶部的距离:

export function getElementFixedTop(elem: HTMLElement) {
  return elem.getBoundingClientRect().top
}