JavaScript检测位置中节点的文本偏移量 [英] JavaScript detect text offset in node at position
问题描述
我想在指定的x和y坐标下检测元素和文本偏移量。
I would like to detect the element and text offset under the specified x and y co-ordinates.
假设我们有这样的DOM:
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>
当用户在单词 _Fusce _ $ c之前点击鼠标时$ c>有x和y坐标我希望在文本节点中获得单词
_Fusce _
的偏移量作为索引。这可能吗?
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?
推荐答案
WebKit有 document.caretRangeFromPoint()
for这个。 CSSOM View规范有 document.caretPositionFromPoint()
,但只有 Firefox 20及更高版本目前正在实施它。
WebKit has document.caretRangeFromPoint()
for this. The CSSOM View spec has document.caretPositionFromPoint()
, but only Firefox 20 and later currently implements it.
在Firefox中,如果您感兴趣的位置来自鼠标事件,那么您可以直接从事件中获取此信息,该事件具有 rangeParent
和 rangeOffset
的属性。
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
这篇关于JavaScript检测位置中节点的文本偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!