How best to convert a ClientRect / DomRect into a plain Object
它的结构类似于
不幸的是,该对象的行为与其他对象不同。
例如,在其上使用
我发现了一种转换为普通对象的肮脏方式:
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())) |