How can I get the DOMRange style offset in the DOM node for a given location of the mouse (or document)?

I know how to determine which DOM nodes intersect with an absolute position. But say the text is node. How to determine the offset in the text node corresponding to this location? I would like to build a DOMRange from a known position to this position.

+4
source share
1 answer

The first step is to find all the Elements that intersect the position. To do this, you must use the Element.getBoundingClientRect method. Then you can easily get all the Text nodes that are inside this Element . The hard part is figuring out what text inside these Text nodes is within these boundaries. You can start with Element.getClientRects to get lines of text inside Element . Here is a great example .

Then you want to build a Range object by changing startOffset and endOffset . You can use the getClientRects method for a Range object.

+1
source

Source: https://habr.com/ru/post/1394727/


All Articles