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

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

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

5条回答
  •  我在风中等你
    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 )
    )

提交回复
热议问题