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
Specification | Status | Comment |
---|---|---|
CSS Object Model (CSSOM) View Module The definition of 'Range.getBoundingClientRect()' in that specification. | Working Draft | Initial specification. |
Browser compatibility
BCD tables only load in the browser
See also
Range.getClientRects()
- finer-grained result for non-rectangular ranges (e.g., when the selection wraps onto the next line);Element.getBoundingClientRect()
Document.caretPositionFromPoint()
- to get the (node, offset) from viewport coordinates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论