如何获取元素中文本的位置? [英] How to get the position of text within an element?

查看:106
本文介绍了如何获取元素中文本的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个元素,例如:

If I have an element, for instance:

<p>Lorem ipsum dolor sit amet, ante risus massa adipiscing quisque quis. At mauris tellus in, sed vehicula integer fermentum rhoncus at faucibus, in vitae purus. Maecenas in vel ligula orci tellus ac, fringilla conubia lorem elit. Dui nulla sodales morbi vel. Massa sed viverra. Maecenas imperdiet donec urna a, ligula sed</p>

这是多行的:

Lorem ipsum dolor sit amet, ante risus massa adipiscing
quisque quis. At mauris tellus in, sed vehicula integer
fermentum rhoncus at faucibus, in vitae purus. Maecenas
in vel ligula orci tellus ac, fringilla conubia lorem
elit. Dui nulla sodales morbi vel. Massa sed viverra.
Maecenas imperdiet donec urna a, ligula sed

是否有可能找到位置(使用Javascript在文本中的特定字符的x,y坐标)?如果没有,我可以获得文本中每一行的y位置吗?

Is it possible to find out the position (in x,y-coordinates) of a particular character in the text using Javascript? If not, could I get the y-position of each line in the text?

请注意:有很多文字在我的应用程序中的< p> 标记,因此在每个字符/单词周围添加< span> 会过多处理。

Please note: There is a lot of text in the <p> tag in my application, so adding <span> around each character/word would be too much processing.

推荐答案

如果您知道文本中字符的字符串位置,则可以将字符包装在< span中>或具有ID的类似元素,并找到该元素的x,y坐标。最简单的方法是使用jQuery或其他库,参见这是一个跨浏览器,无库方法的答案。

If you know the string position of the character in the text, you can wrap the character in a <span> or similar element with an ID and find the x,y coords of that element. Easiest way to do this is with jQuery or another library, see this answer for a cross-browser, no-library method.

这篇关于如何获取元素中文本的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆