我如何相对于文档/窗口获得用户选择的中心锚点位置(x,y)?

发布于 2025-02-11 16:22:59 字数 210 浏览 2 评论 0原文

如何相对于文档/窗口,如何获得用户选择的中心锚点位置(x,y)?

我只知道如何使用window.getSelection()获得选择节点。但不是位置:

示例用例用例

How can I get the user's selection's center anchor point position (x, y) relative to the document/window?

I only know how to get selected nodes using window.getSelection(). But not the position:

example use case

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

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

发布评论

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

评论(1

南汐寒笙箫 2025-02-18 16:23:02

您可以为此目的使用getBoundingClientRect()。要获取中心点,请将宽度的一半添加到距屏幕左边缘的水平距离。

let coords = window.getSelection().getRangeAt(0).getBoundingClientRect()
let center = coords.x + (  coords.width / 2 )

从文档顶部获得准确的垂直位置。

coords.y + window.scrollY

You can use getBoundingClientRect() for this purpose. To get the center point, add the half of width to the horizontal distance from the left edge of the screen.

let coords = window.getSelection().getRangeAt(0).getBoundingClientRect()
let center = coords.x + (  coords.width / 2 )

To get the accurate vertical position from the top of the document.

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