Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 )
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...