Range.getBoundingClientRect()

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

Range.getBoundingClientRect() 返回一个 DOMRect 对象,该对象将范围中的内容包围起来;即该对象是一个将范围内所有元素的边界矩形包围起来的矩形(译者注:关于边界矩形,可以参考 Minimum Bouding Rectangles)。

此方法可用于确定文本区域中选中的部分或光标的视窗坐标。关于返回值的详细信息,参见 Element.getBoundingClientRect()

语法

boundingRect = range.getBoundingClientRect()

示例

HTML

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

CSS

#highlight {
  background: yellow;
  position: absolute;
  z-index: -1;
}

p {
  width: 200px;
}

JavaScript

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

结果

规范

规范 状态 备注
CSS Object Model (CSSOM) View Module
Range.getBoundingClientRect()
Working Draft Initial specification.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
getBoundingClientRect
Experimental
Chrome Full support YesEdge Full support 12Firefox Full support 4IE Full support 9Opera Full support 15Safari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support 14Safari iOS Full support YesSamsung Internet Android Full support Yes

Legend

Full support  
Full support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.

参见