Element.getBoundingClientRect()
method returns the size of an element and its position relative to the viewport.
The element's size is equal to its
width
/
height
+
padding
+
border-width
in the case that the standard box model is being used, or
width
/
height
only if
box-sizing: border-box
has been set on it.
domRect = element.getBoundingClientRect();
The returned value is a
DOMRect
object which is the union of the rectangles returned by
getClientRects()
for the element, i.e., the CSS border-boxes associated with the element. The result is the smallest rectangle which contains the entire element, with read-only
left
,
top
,
right
,
bottom
,
x
,
y
,
width
,和
height
properties describing the overall border-box in pixels. Properties other than
width
and
height
are relative to the top-left of the viewport.
Empty border-boxes are completely ignored. If all the element's border-boxes are empty, then a rectangle is returned with a
width
and
height
of zero and where the
top
and
left
are the top-left of the border-box for the first CSS box (in content order) for the element.
The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the bounding rectangle. This means that the rectangle's boundary edges (
top
,
right
,
bottom
,
left
) change their values every time the scrolling position changes (because their values are relative to the viewport and not absolute).
If you need the bounding rectangle relative to the top-left corner of the document, just add the current scrolling position to the
top
and
left
properties (these can be obtained using
window.scrollX
and
window.scrollY
) to get a bounding rectangle which is independent from the current scrolling position.
Scripts requiring high cross-browser compatibility can use
window.pageXOffset
and
window.pageYOffset
而不是
window.scrollX
and
window.scrollY.
Scripts without access to these properties can use code like this:
// For scrollX (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.scrollLeft == 'number' ? t : document.body).scrollLeft // For scrollY (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.scrollTop == 'number' ? t : document.body).scrollTop
This simple example retrieves the
DOMRect
object representing the bounding client rect of a simple
<div>
element, and prints out its properties below it.
<div></div>
div {
width: 400px;
height: 200px;
padding: 20px;
margin: 50px auto;
background: purple;
}
let elem = document.querySelector('div');
let rect = elem.getBoundingClientRect();
for (var key in rect) {
if(typeof rect[key] !== 'function') {
let para = document.createElement('p');
para.textContent = `${ key } : ${ rect[key] }`;
document.body.appendChild(para);
}
}
Notice how the
width
/
height
are equal to its
width
/
height
+
padding
.
Also note how the values of
x
/
left
,
y
/
top
,
right
,和
bottom
are equal to the absolute distance from the relevant edge of the viewport to that side of the element, in each case.
| 规范 | 状态 | 注释 |
|---|---|---|
|
CSSOM (CSS 对象模型) 视图模块
The definition of 'Element.getBoundingClientRect()' in that specification. |
工作草案 | 初始定义 |
返回的
DOMRect
object can be modified in modern browsers. This was not true with older versions which effectively returned
DOMRectReadOnly
. With IE and Edge, not being able to add missing properties to their returned
ClientRect
, object prevents backfilling
x
and
y
.
Due to compatibility problems (see below), it is safest to rely on only properties
left
,
top
,
right
,和
bottom
.
Properties in the returned
DOMRect
object are not own properties. While the
in
operator and
for...in
will find returned properties, other APIs such as
Object.keys()
will fail. Moreover, and unexpectedly, the ES2015 and newer features such as
Object.assign()
and object rest/spread will fail to copy returned properties.
rect = elt.getBoundingClientRect()
// The result in emptyObj is {}
emptyObj = Object.assign({}, rect)
emptyObj = { ...rect }
{width, ...emptyObj} = rect
DOMRect
properties
top
,
left
,
right
,和
bottom
are computed using the values of the object's other properties.
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
getBoundingClientRect
|
Chrome 2 | Edge 12 | Firefox 3 | IE 4 | Opera 9.5 | Safari 6 | WebView Android ≤37 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 |
Safari iOS
4
|
Samsung Internet Android 1.0 |
height
|
Chrome Yes | Edge 12 | Firefox 3.5 | IE 9 | Opera Yes | Safari Yes | WebView Android Yes | Chrome Android Yes | Firefox Android ? | Opera Android Yes | Safari iOS Yes | Samsung Internet Android Yes |
width
|
Chrome Yes | Edge 12 | Firefox 3.5 | IE 9 | Opera Yes | Safari Yes | WebView Android Yes | Chrome Android Yes | Firefox Android ? | Opera Android Yes | Safari iOS Yes | Samsung Internet Android Yes |
x
|
Chrome Yes | Edge 79 | Firefox Yes |
IE
No
|
Opera Yes | Safari 11 | WebView Android Yes | Chrome Android Yes | Firefox Android ? | Opera Android Yes | Safari iOS 11 | Samsung Internet Android Yes |
y
|
Chrome Yes | Edge 79 | Firefox Yes |
IE
No
|
Opera Yes | Safari 11 | WebView Android Yes | Chrome Android Yes | Firefox Android ? | Opera Android Yes | Safari iOS 11 | Samsung Internet Android Yes |
完整支持
不支持
兼容性未知
见实现注意事项。
getClientRects()
getBoundingClientRect
ClientRect
, an earlier version of
DOMRect
元素
accessKey
属性
childElementCount
children
classList
className
clientHeight
clientLeft
clientTop
clientWidth
currentStyle
firstElementChild
id
innerHTML
lastElementChild
localName
名称
namespaceURI
nextElementSibling
onfullscreenchange
onfullscreenerror
openOrClosedShadowRoot
outerHTML
part
prefix
previousElementSibling
runtimeStyle
scrollHeight
scrollLeft
scrollLeftMax
scrollTop
scrollTopMax
scrollWidth
shadowRoot
slot
tabStop
tagName
after()
animate()
append()
attachShadow()
before()
closest()
computedStyleMap()
createShadowRoot()
getAnimations()
getAttribute()
getAttributeNames()
getAttributeNode()
getAttributeNodeNS()
getAttributeNS()
getBoundingClientRect()
getClientRects()
getElementsByClassName()
getElementsByTagName()
getElementsByTagNameNS()
hasAttribute()
hasAttributeNS()
hasAttributes()
hasPointerCapture()
insertAdjacentElement()
insertAdjacentHTML()
insertAdjacentText()
matches()
msZoomTo()
prepend()
querySelector()
querySelector()
querySelectorAll()
querySelectorAll()
releasePointerCapture()
remove()
removeAttribute()
removeAttributeNode()
removeAttributeNS()
replaceChildren()
replaceWith()
requestFullscreen()
requestPointerLock()
scroll()
scrollBy()
scrollIntoView()
scrollIntoViewIfNeeded()
scrollTo()
setAttribute()
setAttributeNode()
setAttributeNodeNS()
setAttributeNS()
setCapture()
setPointerCapture()
toggleAttribute()
afterscriptexecute
auxclick
blur
click
compositionend
compositionstart
compositionupdate
contextmenu
copy
cut
dblclick
DOMActivate
DOMMouseScroll
error
focus
focusin
focusout
fullscreenchange
fullscreenerror
gesturechange
gestureend
gesturestart
keydown
keypress
keyup
mousedown
mouseenter
mouseleave
mousemove
mouseout
mouseover
mouseup
mousewheel
MozMousePixelScroll
msContentZoom
MSGestureChange
MSGestureEnd
MSGestureHold
MSGestureStart
MSGestureTap
MSInertiaStart
MSManipulationStateChanged
overflow
paste
scroll
select
show
touchcancel
touchend
touchmove
touchstart
underflow
webkitmouseforcechanged
webkitmouseforcedown
webkitmouseforceup
webkitmouseforcewillbegin
wheel
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
Document
DocumentFragment
DocumentType
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument