获取句子开头和结尾的坐标

发布于 2024-12-04 00:51:00 字数 577 浏览 1 评论 0原文

我有一个 ,其中包含一个句子。例如:

<span>A sentence residing within a span</span>

是否可以在附加到该跨度的 Javascript 事件(例如 onmouseover)上分别获取该句子的开头和结尾字母(即“A”和“n”)的坐标?

该跨度位于 div 内。所以

case - I:对于句子

This is a sentence inline

The top and left 是根据单词“This”的字母“T”进行评估的。

case - II:对于句子

... ... ... ... ... ... This is
a sentence broke into two lines.

顶部根据单词“This”的字母“T”进行评估,左侧根据“a”进行评估。

有没有办法获取一个句子的两个端点的坐标?

I have a <span></span>, within which a sentence resides. Like:

<span>A sentence residing within a span</span>

Is it possible to get the coordinates of the starting and ending letters of that sentence i.e "A" and "n" respectively on a Javascript event like onmouseover attached with that span?

The span is resides within a div. So

case - I: for the sentence

This is a sentence inline

The top and left is evaluated with respect to the letter "T" of the word "This".

case - II: for the sentence

... ... ... ... ... ... This is
a sentence broke into two lines.

The top is evaluated with respect to the letter "T" of the word "This" and the left is evaluated with respect to "a".

Is there any way to get the coordinates of the two terminals of a sentence?

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

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

发布评论

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

评论(2

几度春秋 2024-12-11 00:51:00

span.getBoundingClientRect()文档

span.getBoundingClientRect()? docs

噩梦成真你也成魔 2024-12-11 00:51:00

如果您想要句子第一个字符的左上角和最后一个字符的右下角的坐标,可以使用 元素的getClientRects()方法。 所有主要浏览器的最新版本均支持

var rects = span.getClientRects();
var startTopLeft = { x: rects[0].left, y: rects[0].top; };
var lastRect = rects[rects.length - 1];
var endBottomRight = { x: lastRect.right, y: lastRect.bottom; };

请注意,这些坐标是相对于视口而不是文档的。如果您需要使用这些坐标来定位其他元素,则需要考虑滚动。

If you want the coordinates of the top left of the first character and the bottom right of the last character of the sentence, you can use the getClientRects() method of the element. It's supported in recent versions of all major browsers.

var rects = span.getClientRects();
var startTopLeft = { x: rects[0].left, y: rects[0].top; };
var lastRect = rects[rects.length - 1];
var endBottomRight = { x: lastRect.right, y: lastRect.bottom; };

Note that these coordinates are relative to the viewport rather than the document. If you need to position other elements using these coordinates, you'll need to account for scrolling.

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