Get the position of text within an element

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 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 coords) of a particular character in the text using JavaScript? Failing this could I get the y position of each line in the flowed text?

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.


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.


You can use ranges to find the position of elements. Quick jsfiddle here: 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


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

链接地址: http://www.djcxy.com/p/15616.html

上一篇: 如何使用javascript获取左上角的x和y坐标

下一篇: 获取元素内文本的位置