如何最好地将ClientRect / DomRect转换为普通对象 [英] How best to convert a ClientRect / DomRect into a plain Object

查看:547
本文介绍了如何最好地将ClientRect / DomRect转换为普通对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

someElement.getBoundingClientRect()的结果返回类型 ClientRect 特殊对象>(或显然 DomRect

The result of someElement.getBoundingClientRect() returns a special object of type ClientRect (or DomRect apparently)

它的结构类似于 {top:10,right :20,底部:30,左:10,宽度:10}

不幸的是,此对象的行为与其他对象不同。

Unfortunately, this object does not behave quite like other objects.

例如,使用 Object.keys 就会返回一个空数组(我想是因为 ClientRect 属性不是可枚举的

For example, using Object.keys on it returns an empty array (I think because ClientRect properties are not enumerable

我发现了一些转换为普通对象的脏方法:

I found something of a dirty way to convert to a plain object:

var obj = {}
for (key in rect) {
  obj[key] = rect[key]
}

我的问题是,有更好的方法吗?

推荐答案

让我们不要过于复杂化!

Let's not overcomplicate things!

function getBoundingClientRect(element) {
  const rect = element.getBoundingClientRect();
  return {
    top: rect.top,
    right: rect.right,
    bottom: rect.bottom,
    left: rect.left,
    width: rect.width,
    height: rect.height,
    x: rect.x,
    y: rect.y
  };
}

这篇关于如何最好地将ClientRect / DomRect转换为普通对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆