The Element.getBoundingClientRect() method returns a DOMRect object providing information about the kích cỡ of an element & its position relative to the viewport.
The width and height properties of theDOMRect object returned by the method include the padding & border-width, not only the nội dung width/height. In the standard box Mã Sản Phẩm, this would be equal khổng lồ thewidth or height property of the element + padding+border-width. But ifbox-sizing: border-box is mix for the element this would be directly equal to lớn itswidth or height.
The returned value can be thought of as the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.
Empty border-boxes are completely ignored. If all the element"s border-boxes are empty, then a rectangle is returned with a width & height of zero and where the top và left are the top-left of the border-box for the first CSS box (in content order) for the element.
If you need the bounding rectangle relative sầu lớn the top-left corner of the document, just add the current scrolling position to the top & left properties (these can be obtained using window.scrollX and window.scrollY) lớn get a bounding rectangle which is independent from the current scrolling position.
Scripts requiring high cross-browser compatibility can use window.pageXOffmix and window.pageYOffmix instead of window.scrollX and window.scrollY. Scripts without access khổng lồ these properties can use code lượt thích this:
// For scrollX(((t = document.documentElement) || (t = document.body toàn thân.parentNode)) && typeof t.scrollLeft == "number" ? t : document.body).scrollLeft// For scrollY(((t = document.documentElement) || (t = document.toàn thân.parentNode)) && typeof t.scrollTop == "number" ? t : document.body).scrollTop
BasicThis simple example retrieves the DOMRect object representing the bounding client rect of a simple element, & prints out its properties below it.
div>div>The returned DOMRect object can be modified in modern browsers. This was not true with older versions which effectively returned DOMRectReadOnly. With IE và Edge, not being able to add missing properties to lớn their returned ClientRect, object prevents backfilling x and y.
Due to lớn compatibility problems (see below), it is safest to lớn rely on only properties left, top, right, & bottom.
rect = elt.getBoundingClientRect()// The result in emptyObj is emptyObj = Object.assign(, rect)emptyObj = ...rect width, ...emptyObj = rectDOMRect properties top,left, right, & bottom are computed using the values of the object"s other properties.