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

问题描述

js 复制代码
export function capture(key: string | number, el: HTMLElement | null): void {
  if (!el) return

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

  // ....
}

打印结果如下:

底层原理

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

解决方案

手动解构

js 复制代码
 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)
}

此时打印结果:

相关推荐
沙蒿同学11 分钟前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端
甜到心里的蛋糕32 分钟前
加解密技术详解:纯前端如何实现 AES / SM4 / RSA / 国密 SM2
前端·密码学
拖孩1 小时前
代码我能全交给 AI,流量主这 500 个访客它一个都替不了我
前端·后端·微信小程序
2601_963870211 小时前
基于SSM的特产代购系统
java·前端
paopaokaka_luck1 小时前
智慧社区综合服务小程序(人脸识别、AI问答、Echarts图形化分析)
前端·javascript·spring boot·spring·数据分析·echarts
烈风逍遥1 小时前
第七篇:提示词模板管理与 Agent 提示词编排
前端·人工智能·后端
Amos_Web2 小时前
Rspack 源码解析(十二):JavaScript Chunk 是如何被渲染出来的
前端·rust·源码
前端探险家Rick2 小时前
React Native 二级弹出面板 + 键盘适配:从踩坑到正确方案
前端
用户921080262862 小时前
MCP 是什么?用 Figma MCP 辅助还原 Vue 页面
前端
用户921080262862 小时前
用 Figma MCP 还原 Vue 页面时,我遇到的三个问题
前端