扩展运算符无法克隆 getBoundingClientRect() 获取的值

50 阅读1分钟

问题描述

export function capture(key: string | number, el: HTMLElement | null): void {
  if (!el) return

  const rect = el.getBoundingClientRect()
  console.log('获取到的值', rect, '展开时', { ...rect })

  // ....
}

打印结果如下:

image.png

底层原理

getBoundingClientRect() 返回的是一个 DOMRect 对象。在 JS 中,DOMRect 的属性(left, top 等)是定义在 原型链(Prototype) 上的 getter,而不是对象自身的 enumerable 属性。因此,使用 {...rect} 扩展运算符无法克隆出这些值。

解决方案

手动解构

 export function capture(key: string | number, el: HTMLElement | null): void {
  if (!el) return

  const rect = el.getBoundingClientRect()
  const computedStyle = window.getComputedStyle(el)

  const info = {
    left: rect.left,
    top: rect.top,
    width: rect.width,
    height: rect.height,
    x: rect.x,
    y: rect.y,
    fontSize: parseFloat(computedStyle.fontSize) || undefined
  }
  
 console.log('info', info)
}

此时打印结果: image.png