getClientRects()
方法在
元素
interface returns a collection of
DOMRect
objects that indicate the bounding rectangles for each
CSS border box
in a client.
let rectCollection = object.getClientRects();
The returned value is a collection of
DOMRect
objects, one for each CSS border box associated with the element. Each
DOMRect
object contains read-only
left
,
top
,
right
and
bottom
properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport. For tables with captions, the caption is included even though it's outside the border box of the table. When called on SVG elements other than an outer-
<svg>
, the "viewport" that the resulting rectangles are relative to is the viewport that the element's outer-
<svg>
establishes (and to be clear, the rectangles are also transformed by the outer-
<svg>
's
viewBox
transform, if any).
Originally, Microsoft intended this method to return a
TextRectangle
object for each
line
of text. However, the CSSOM working draft specifies that it returns a
DOMRect
for each
border box
. For an inline element, the two definitions are the same. But for a block element, Mozilla will return only a single rectangle.
Firefox 3.5 adds
width
and
height
properties to the
TextRectangle
对象。
The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the rectangles.
The returned rectangles do not include the bounds of any child elements that might happen to overflow.
For HTML
<area>
elements, SVG elements that do not render anything themselves,
display:none
elements, and generally any elements that are not directly rendered, an empty list is returned.
Rectangles are returned even for CSS boxes that have empty border-boxes. The
left
,
top
,
right
,和
bottom
coordinates can still be meaningful.
Fractional pixel offsets are possible.
These examples draw client rects in various colors. Note that the JavaScript function that paints the client rects is connected to the markup via the class
withClientRectsOverlay
.
Example 1: This HTML creates three paragraphs with a
<span>
inside, each embedded in a
<div>
block. Client rects are painted for the paragraph in the second block, and for the
<span>
element in the third block.
<h3>A paragraph with a span inside</h3>
<p>Both the span and the paragraph have a border set. The
client rects are in red. Note that the p has onlyone border
box, while the span has multiple border boxes.</p>
<div>
<strong>Original</strong>
<p>
<span>Paragraph that spans multiple lines</span>
</p>
</div>
<div>
<strong>p's rect</strong>
<p class="withClientRectsOverlay">
<span>Paragraph that spans multiple lines</span>
</p>
</div>
<div>
<strong>span's rect</strong>
<p>
<span class="withClientRectsOverlay">Paragraph that spans multiple lines</span>
</p>
</div>
Example 2: This HTML creates three ordered lists. Client rects are painted for the
<ol>
in the second block, and for each
<li>
element in the third block.
<h3>A list</h3>
<p>Note that the border box doesn't include the number, so
neither do the client rects.</p>
<div>
<strong>Original</strong>
<ol>
<li>Item 1</li>
<li>Item 2</li>
</ol>
</div>
<div>
<strong>ol's rect</strong>
<ol class="withClientRectsOverlay">
<li>Item 1</li>
<li>Item 2</li>
</ol>
</div>
<div>
<strong>each li's rect</strong>
<ol>
<li class="withClientRectsOverlay">Item 1</li>
<li class="withClientRectsOverlay">Item 2</li>
</ol>
</div>
Example 3: This HTML creates two tables with captions. Client rects are painted for the
<table>
in the second block.
<h3>A table with a caption</h3> <p>Although the table's border box doesn't include the caption, the client rects do include the caption.</p> <div> <strong>Original</strong> <table> <caption>caption</caption> <thead> <tr><th>thead</th></tr> </thead> <tbody> <tr><td>tbody</td></tr> </tbody> </table> </div> <div> <strong>table's rect</strong> <table class="withClientRectsOverlay"> <caption>caption</caption> <thead> <tr><th>thead</th></tr> </thead> <tbody> <tr><td>tbody</td></tr> </tbody> </table> </div>
The CSS draws borders around the paragraph and the
<span>
inside each
<div>
block for the first example, around the
<ol>
and
<li>
for the second example, and around
<table>
,
<th>
,和
<td>
elements for the third example.
strong {
text-align: center;
}
div {
display: inline-block;
width: 150px;
}
div p, ol, table {
border: 1px solid blue;
}
span, li, th, td {
border: 1px solid green;
}
The JavaScript code draws the client rects for all HTML elements that have CSS class
withClientRectsOverlay
assigned.
function addClientRectsOverlay(elt) {
/* Absolutely position a div over each client rect so that its border width
is the same as the rectangle's width.
Note: the overlays will be out of place if the user resizes or zooms. */
var rects = elt.getClientRects();
for (var i = 0; i != rects.length; i++) {
var rect = rects[i];
var tableRectDiv = document.createElement('div');
tableRectDiv.style.position = 'absolute';
tableRectDiv.style.border = '1px solid red';
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
tableRectDiv.style.margin = tableRectDiv.style.padding = '0';
tableRectDiv.style.top = (rect.top + scrollTop) + 'px';
tableRectDiv.style.left = (rect.left + scrollLeft) + 'px';
// We want rect.width to be the border width, so content width is 2px less.
tableRectDiv.style.width = (rect.width - 2) + 'px';
tableRectDiv.style.height = (rect.height - 2) + 'px';
document.body.appendChild(tableRectDiv);
}
}
(function() {
/* Call function addClientRectsOverlay(elt) for all elements with
assigned class "withClientRectsOverlay" */
var elt = document.getElementsByClassName('withClientRectsOverlay');
for (var i = 0; i < elt.length; i++) {
addClientRectsOverlay(elt[i]);
}
})();
| 规范 | 状态 | 注释 |
|---|---|---|
|
CSSOM (CSS 对象模型) 视图模块
The definition of 'Element.getClientRects()' in that specification. |
工作草案 | 初始定义 |
getClientRects()
was first introduced in the MS IE DHTML object model.
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
getClientRects
|
Chrome 2 | Edge 12 | Firefox 3 | IE 8 | Opera 9.5 | Safari 6 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 6 | Samsung Internet Android 1.0 |
完整支持
元素
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