扩展运算符无法克隆 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)
}

此时打印结果:

相关推荐
jktantan5 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
前端·javascript·vue.js
总要学点什么5 小时前
第89篇:三维特效-螺旋圆效果——让螺旋臂卷起一圈圈外扩的涟漪
开发语言·javascript·ecmascript·webgl·cesium·空间分析·1024程序员节
2601_962885726 小时前
quotes 字段全解:涨跌幅、振幅、换手率的口径与单位
java·前端·spring
excel6 小时前
encodeURI 和 encodeURIComponent 有什么区别?
前端
前端精髓6 小时前
调用openrouter的免费API模型
java·前端·javascript
赛博守夜人6 小时前
AI安全攻防与治理之十四:AI 安全测试不能脱离传统安全,Web、API、移动端与模型攻击面的组合拳
前端·人工智能·安全
开开心心_Every6 小时前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
networknomad7 小时前
OpenReplay:自己搭的会话回放工具,给前端排错用的
前端·其他
缓慢更新8 小时前
AI 辅助生成单测:从接口定义到用例的流水线
java·服务器·前端·网络·数据库·人工智能
陈随易8 小时前
AI 运维服务器,安全又可靠的方法
前端·后端·程序员