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

后端 未结 5 1030
遇见更好的自我
遇见更好的自我 2020-12-20 11:00

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

相关标签:
5条回答
  • 2020-12-20 11:43

    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();
    
    0 讨论(0)
  • 2020-12-20 11:55

    This is something that I can live with:

    const persistRect = JSON.parse(JSON.stringify(someElement.getBoundingClientRect()))
    
    0 讨论(0)
  • 2020-12-20 12:04

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

    var obj = $.extend( {}, element.getBoundingClientRect());
    
    0 讨论(0)
  • 2020-12-20 12:06

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

    0 讨论(0)
  • 2020-12-20 12:07

    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())
    
    0 讨论(0)
提交回复
热议问题