关于javascript:如何最好地将ClientRect / DomRect转换为纯对象

How best to convert a ClientRect / DomRect into a plain Object

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

它的结构类似于{top: 10, right: 20, bottom: 30, left: 10, width: 10}

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

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

我发现了一种转换为普通对象的肮脏方式:

1
2
3
4
var obj = {}
for (key in rect) {
  obj[key] = rect[key]
}

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


让我们不要过于复杂!

1
2
3
4
5
6
7
8
9
10
11
12
13
function getBoundingClientRect(element) {
  var 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
  };
}

ES2015:

1
2
3
4
5
6
7
8
const getBoundingClientRect = element =;gt; {
  const {top, right, bottom, left, width, height, x, y} = element.getBoundingClientRect()
  return {top, right, bottom, left, width, height, x, y}
}

console.log(
  getBoundingClientRect( document.body )
)


如果使用的是jQuery,则可以使用extend方法。

1
var obj = $.extend( {}, element.getBoundingClientRect());


Warning: non-standard behavior (doesn't work in Firefox ;lt; 62, including ESR 60 and possibly other browsers other than Chrome)

1
var obj = el.getBoundingClientRect().toJSON();


功能性ES6变体:

1
2
3
const propValueSet = (prop) =;gt; (value) =;gt; (obj) =;gt; ({...obj, [prop]: value})
const toObj = keys =;gt; obj =;gt; keys.reduce((o, k) =;gt; propValueSet(k)(obj[k])(o), {})
const getBoundingClientRect = el =;gt; toObj(['top', 'right', 'bottom', 'left', 'width', 'height', 'x', 'y'])(el.getBoundingClientRect())

这是我可以接受的:

1
const persistRect = JSON.parse(JSON.stringify(someElement.getBoundingClientRect()))