JavaScript detect text offset in node at position

2019-06-03 14:27发布

问题:

I would like to detect the element and text offset under the specified x and y co-ordinates.

Let's say we have such DOM:

<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Nam quis nisl lectus. Donec euismod dignissim turpis, nec 
viverra nulla iaculis nec. _Fusce_ mattis orci eget nibh 
rhoncus auctor at in enim.
</p>

When the user clicks the mouse just before the word _Fusce_ having the x and y co-ordinates I would like to obtain the offset of the word _Fusce_ in the text node as an index. Is this possible?

回答1:

WebKit has document.caretRangeFromPoint() for this. The CSSOM View spec has document.caretPositionFromPoint(), but only Firefox 20 and later currently implements it.

In Firefox, if the position you're interested in has come from a mouse event then you can get this information direct from the event, which has properties rangeParent and rangeOffset.

Here's a similar question with some example code:

https://stackoverflow.com/a/10659990/96100