神秘布偶猫

Oyiso's xLog

决定性瞬间
github

Using getBoundingClientRect() method in JavaScript to get the precise distance of elements

Using the node.offsetWidth method can retrieve the width of an element, similar methods include:

  • offsetHeight
  • offsetTop
  • offsetBottm
  • offsetLeft
  • offsetRight

Issue Arising#

The values obtained through the offset method are rounded using rounding, however, in some cases during development, precise values are needed. In such cases, using the offset method may not be feasible.

Solution#

By using the getBoundingClientRect() method, precise values of the element can be obtained (accurate to 6 decimal places).

Usage#

For example, node.getBoundingClientRect().width can retrieve the width of the element, similar methods include:

  • getBoundingClientRect().height
  • getBoundingClientRect().top
  • getBoundingClientRect().bottom
  • getBoundingClientRect().left
  • getBoundingClientRect().right

Explanation#

getBoundingClientRect() returns a collection of rectangles. It represents the position of the current element in the browser and the space it occupies. Apart from width and height, other properties are calculated relative to the top left corner of the viewport, as shown in the image:

image

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.