use-client-rect.ts 1.1 KB
Newer Older
Y
yewenwen3 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/**
  获取元素的大小及其相对于视口的位置,等价于 Element.getBoundingClientRect。
  width 宽度	number
  height 高度	number
  top	顶部与视图窗口左上角的距离	number
  left	左侧与视图窗口左上角的距离	number
  right	右侧与视图窗口左上角的距离	number
  bottom	底部与视图窗口左上角的距离	number
 */

function isWindow(val: unknown): val is Window {
  return val === window
}

15
export const getRect = (elementRef: Element | Window | undefined) => {
Y
yewenwen3 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  const element = elementRef

  if (isWindow(element)) {
    const width = element.innerWidth
    const height = element.innerHeight

    return {
      top: 0,
      left: 0,
      right: width,
      bottom: height,
      width,
      height,
    }
  }

  if (element && element.getBoundingClientRect) {
    return element.getBoundingClientRect()
  }

  return {
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    width: 0,
    height: 0,
  }
}
X
xiaoyatong 已提交
45 46

export const getRectByTaro = async (element: any) => {
47 48 49 50 51
  if (element) {
    const res = await element.getBoundingClientRect()
    return res
  }
  return Promise.resolve({})
X
xiaoyatong 已提交
52
}