对于文本节点是否有与 getBoundingClientRect() 等效的方法?

发布于 2024-08-05 16:06:19 字数 82 浏览 5 评论 0原文

有没有办法获取文本节点的边界矩形?

getBoundingClientRect() 方法仅在元素上定义,并且父元素比实际文本节点大。

Is there a way to get the bounding rect of a text node?

The getBoundingClientRect() method is defined on elements only, and the parent element is bigger then the actual text node.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小瓶盖 2024-08-12 16:06:19

如果您不需要支持 IE8 或更早版本,则可以使用 Range< /code>选择文本节点,然后直接从 Range 获取边界矩形。

示例(应该在此页面中工作):

var text = document.querySelector('#question-header .question-hyperlink').childNodes[0];
var range = document.createRange();
range.selectNode(text);
var rect = range.getBoundingClientRect();
range.detach(); // frees up memory in older browsers

如果您要对多个文本节点执行此操作,您还可以重用 Range 对象;只需确保在完成之前不要调用 range.detach() 即可。 (注意:Range.detach() 现在是 DOM 标准,尽管一些较旧的浏览器在调用后仍会禁用该范围。)

If you don't need to support IE8 or older, you can use a Range to select the text node, and then get the bounding rect directly from the Range.

Example (should work in this page):

var text = document.querySelector('#question-header .question-hyperlink').childNodes[0];
var range = document.createRange();
range.selectNode(text);
var rect = range.getBoundingClientRect();
range.detach(); // frees up memory in older browsers

You can also reuse the Range object if you're doing this for multiple text nodes; just make sure not to call range.detach() until you're done. (Note: Range.detach() is now a no-op in the DOM standard, though some older browsers will still disable use of the range after its invocation.)

静谧 2024-08-12 16:06:19

将文本节点包裹在 中,获取该 span 的 boundingRect

var span = document.createElement('span');
textNode.parentNode.insertBefore(span, textNode);
span.appendChild(textNode);
var rect = span.getBoundingClientRect();

Wrap the text node in a <span>, get the boundingRect of that span.

var span = document.createElement('span');
textNode.parentNode.insertBefore(span, textNode);
span.appendChild(textNode);
var rect = span.getBoundingClientRect();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文