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

此时打印结果:

相关推荐
忆江南2 小时前
# Flutter 语音房礼物下载方案(完整版)
前端
悟空瞎说2 小时前
React 19 带来了诸多创新
前端·react.js
im_AMBER2 小时前
高并发下的列表乱序与文档同步
前端·react.js·架构
游戏开发爱好者82 小时前
React Native iOS 代码如何加密,JS 打包 和 IPA 混淆
android·javascript·react native·ios·小程序·uni-app·iphone
前进的李工2 小时前
LangChain使用之Model IO(提示词模版之ChatPromptTemplate)
java·前端·人工智能·python·langchain·大模型
漫随流水2 小时前
旅游推荐系统(login.html)
前端·html·旅游
1024小神2 小时前
记录xcode项目swiftui配置APP加载启动图
前端·ios·swiftui·swift
CHU7290353 小时前
社区生鲜买菜小程序前端功能版块设计及玩法介绍
前端·小程序
尤山海3 小时前
深度防御:内容类网站如何有效抵御 SQL 注入与脚本攻击(XSS)
前端·sql·安全·web安全·性能优化·状态模式·xss