JavaScript detect text offset in node at position

吃可爱长大的小学妹 提交于 2019-12-08 04:50:19

问题


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



来源:https://stackoverflow.com/questions/12705781/javascript-detect-text-offset-in-node-at-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!