--- title: Range.getBoundingClientRect() slug: Web/API/Range/getBoundingClientRect tags: - API - CSSOM View - Method - Range - 域 - 方法 - 范围 translation_of: Web/API/Range/getBoundingClientRect ---
Range.getBoundingClientRect()
返回一个 {{ domxref("DOMRect") }} 对象,该对象将范围中的内容包围起来;即该对象是一个将范围内所有元素的边界矩形包围起来的矩形(译者注:关于边界矩形,可以参考 Minimum Bouding Rectangles)。
此方法可用于确定文本区域中选中的部分或光标的视窗坐标。关于返回值的详细信息,参见 {{domxref("Element.getBoundingClientRect()")}}。
boundingRect = range.getBoundingClientRect()
<div id="highlight"></div> <p>This example positions a "highlight" rectangle behind the contents of a range. The range's content <b>starts here</b> and continues on until it <b>ends here</b>. The bounding client rectangle contains everything selected in the range.</p>
#highlight { background: yellow; position: absolute; z-index: -1; } p { width: 200px; }
const range = document.createRange(); range.setStartBefore(document.getElementsByTagName('b').item(0), 0); range.setEndAfter(document.getElementsByTagName('b').item(1), 0); const clientRect = range.getBoundingClientRect(); const highlight = document.getElementById('highlight'); highlight.style.left = `${clientRect.x}px`; highlight.style.top = `${clientRect.y}px`; highlight.style.width = `${clientRect.width}px`; highlight.style.height = `${clientRect.height}px`;
{{EmbedLiveSample("Example")}}
{{Compat}}