someElement.getBoundingClientRect()
的结果返回一个类型为 ClientRect
(或显然是 DomRect
)的特殊对象)
它的结构类似于{top: 10, right: 20, bottom: 30, left: 10, width: 10}
不幸的是,这个对象的行为与其他对象不太一样。
例如,在其上使用 Object.keys
返回一个空数组(我认为是因为 ClientRect
属性不是可枚举的
我发现了一些转换为普通对象的肮脏方法:
var obj = {}
for (key in rect) {
obj[key] = rect[key]
}
我的问题是,有更好的方法吗?
最佳答案
我们不要把事情想得太复杂!
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 )
)
关于javascript - 如何最好地将 ClientRect/DomRect 转换为普通对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39417566/