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

我与影子孤独终老i 提交于 2019-12-29 08:27:34

问题


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

It is structured like {top: 10, right: 20, bottom: 30, left: 10, width: 10}

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

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]
}

My question is, is there a better way?


回答1:


Let's not overcomplicate things!

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:

const getBoundingClientRect = element => { 
  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 )
)



回答2:


You could use the extend method if you are using jQuery.

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



回答3:


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

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



回答4:


This is something that I can live with:

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



回答5:


Functional ES6 variant:

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


来源:https://stackoverflow.com/questions/39417566/how-best-to-convert-a-clientrect-domrect-into-a-plain-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!