开发者

How to 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, fringil开发者_如何学编程la 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?

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.


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜