javascript 如何获取元素中文本的位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5143534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:08:29  来源:igfitidea点击:

How to get the position of text within an element?

javascripthtml

提问by Jamie

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>

And this is flowed across multiple lines:

这是跨越多行的:

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

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?

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

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.

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

采纳答案by glomad

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 thisanswer for a cross-browser, no-library method.

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

回答by aaron

You can use ranges to find the position of elements. Quick jsfiddle here: https://jsfiddle.net/abrady0/ggr5mu7o/

您可以使用范围来查找元素的位置。快速jsfiddle在这里:https://jsfiddle.net/abrady0/ggr5mu7o/

var range = document.createRange();
range.setStart(parentElt, start);
range.setEnd(parentElt, end);
// These rects contain the client coordinates in top, left
var rects = range.getClientRects();

Edit: modified to print out the coordinates of the matched rect

编辑:修改为打印出匹配矩形的坐标

回答by SergeS

Idea i get is - get all the text , pack required substring into span-s , replace innerHTML of element , and get position of span-s

我得到的想法是 - 获取所有文本,将所需的子字符串打包到 span-s 中,替换元素的innerHTML,并获取 span-s 的位置