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 note

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 .

HTML

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>
					

CSS

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;
}
					

JavaScript

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.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
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

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改:
  1. DOM (文档对象模型)
  2. 元素
  3. 特性
    1. accessKey
    2. 属性
    3. childElementCount
    4. children
    5. classList
    6. className
    7. clientHeight
    8. clientLeft
    9. clientTop
    10. clientWidth
    11. currentStyle
    12. firstElementChild
    13. id
    14. innerHTML
    15. lastElementChild
    16. localName
    17. 名称
    18. namespaceURI
    19. nextElementSibling
    20. onfullscreenchange
    21. onfullscreenerror
    22. openOrClosedShadowRoot
    23. outerHTML
    24. part
    25. prefix
    26. previousElementSibling
    27. runtimeStyle
    28. scrollHeight
    29. scrollLeft
    30. scrollLeftMax
    31. scrollTop
    32. scrollTopMax
    33. scrollWidth
    34. shadowRoot
    35. slot
    36. tabStop
    37. tagName
  4. 方法
    1. after()
    2. animate()
    3. append()
    4. attachShadow()
    5. before()
    6. closest()
    7. computedStyleMap()
    8. createShadowRoot()
    9. getAnimations()
    10. getAttribute()
    11. getAttributeNames()
    12. getAttributeNode()
    13. getAttributeNodeNS()
    14. getAttributeNS()
    15. getBoundingClientRect()
    16. getClientRects()
    17. getElementsByClassName()
    18. getElementsByTagName()
    19. getElementsByTagNameNS()
    20. hasAttribute()
    21. hasAttributeNS()
    22. hasAttributes()
    23. hasPointerCapture()
    24. insertAdjacentElement()
    25. insertAdjacentHTML()
    26. insertAdjacentText()
    27. matches()
    28. msZoomTo()
    29. prepend()
    30. querySelector()
    31. querySelector()
    32. querySelectorAll()
    33. querySelectorAll()
    34. releasePointerCapture()
    35. remove()
    36. removeAttribute()
    37. removeAttributeNode()
    38. removeAttributeNS()
    39. replaceChildren()
    40. replaceWith()
    41. requestFullscreen()
    42. requestPointerLock()
    43. scroll()
    44. scrollBy()
    45. scrollIntoView()
    46. scrollIntoViewIfNeeded()
    47. scrollTo()
    48. setAttribute()
    49. setAttributeNode()
    50. setAttributeNodeNS()
    51. setAttributeNS()
    52. setCapture()
    53. setPointerCapture()
    54. toggleAttribute()
  5. 事件
    1. afterscriptexecute
    2. auxclick
    3. blur
    4. click
    5. compositionend
    6. compositionstart
    7. compositionupdate
    8. contextmenu
    9. copy
    10. cut
    11. dblclick
    12. DOMActivate
    13. DOMMouseScroll
    14. error
    15. focus
    16. focusin
    17. focusout
    18. fullscreenchange
    19. fullscreenerror
    20. gesturechange
    21. gestureend
    22. gesturestart
    23. keydown
    24. keypress
    25. keyup
    26. mousedown
    27. mouseenter
    28. mouseleave
    29. mousemove
    30. mouseout
    31. mouseover
    32. mouseup
    33. mousewheel
    34. MozMousePixelScroll
    35. msContentZoom
    36. MSGestureChange
    37. MSGestureEnd
    38. MSGestureHold
    39. MSGestureStart
    40. MSGestureTap
    41. MSInertiaStart
    42. MSManipulationStateChanged
    43. overflow
    44. paste
    45. scroll
    46. select
    47. show
    48. touchcancel
    49. touchend
    50. touchmove
    51. touchstart
    52. underflow
    53. webkitmouseforcechanged
    54. webkitmouseforcedown
    55. webkitmouseforceup
    56. webkitmouseforcewillbegin
    57. wheel
  6. 继承:
    1. 节点
    2. EventTarget
  7. DOM 相关页面
    1. AbortController
    2. AbortSignal
    3. AbstractRange
    4. Attr
    5. ByteString
    6. CDATASection
    7. CSSPrimitiveValue
    8. CSSValue
    9. CSSValueList
    10. CharacterData
    11. ChildNode
    12. 注释
    13. CustomEvent
    14. DOMConfiguration
    15. DOMError
    16. DOMErrorHandler
    17. DOMException
    18. DOMImplementation
    19. DOMImplementationList
    20. DOMImplementationRegistry
    21. DOMImplementationSource
    22. DOMLocator
    23. DOMObject
    24. DOMParser
    25. DOMPoint
    26. DOMPointInit
    27. DOMPointReadOnly
    28. DOMRect
    29. DOMString
    30. DOMTimeStamp
    31. DOMTokenList
    32. DOMUserData
    33. Document
    34. DocumentFragment
    35. DocumentType
    36. ElementTraversal
    37. Entity
    38. EntityReference
    39. 事件
    40. EventTarget
    41. HTMLCollection
    42. MutationObserver
    43. 节点
    44. NodeFilter
    45. NodeIterator
    46. NodeList
    47. NonDocumentTypeChildNode
    48. ProcessingInstruction
    49. PromiseResolver
    50. 范围
    51. StaticRange
    52. 文本
    53. TextDecoder
    54. TextEncoder
    55. TimeRanges
    56. TreeWalker
    57. TypeInfo
    58. USVString
    59. UserDataHandler
    60. XMLDocument