Range.getBoundingClientRect() - Web APIs 编辑

Experimental

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The Range.getBoundingClientRect() method returns a DOMRect object that bounds the contents of the range; this is a rectangle enclosing the union of the bounding rectangles for all the elements in the range.

This method is useful for determining the viewport coordinates of the cursor or selection inside a text box. See Element.getBoundingClientRect() for details on the returned value.

Syntax

boundingRect = range.getBoundingClientRect()

Example

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

Result

Specifications

SpecificationStatusComment
CSS Object Model (CSSOM) View Module
The definition of 'Range.getBoundingClientRect()' in that specification.
Working DraftInitial specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:140 次

字数:4264

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文