How best to convert a ClientRect / DomRect into a

2019-06-15 13:40发布

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?

4条回答
淡お忘
2楼-- · 2019-06-15 14:14

This is something that I can live with:

const persistRect = JSON.parse(JSON.stringify(someElement.getBoundingClientRect()))
查看更多
Explosion°爆炸
3楼-- · 2019-06-15 14:27

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();
查看更多
倾城 Initia
4楼-- · 2019-06-15 14:31

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

var obj = $.extend( {}, element.getBoundingClientRect());
查看更多
时光不老,我们不散
5楼-- · 2019-06-15 14:39

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
  };
}
查看更多
登录 后发表回答