[英]Finding the current caret position in a contenteditable div?
I have a contenteditable div . 我有一个内容可编辑的div 。 I want to colorize specific text (which is like A4 , D12 etc) while typing. 我想在键入时为特定文本着色(如A4 , D12等)。
So on each keypress i check the content of div
, find out the tokens(A4,D11 etc) and wrap them into span
. 因此,在每次按键时,我都要检查div
的内容,找出标记(A4,D11等)并将它们包装成span
。
So abcd+A6
will get converted as abcd+<span color=#some-color>A6</span>
因此abcd+A6
将转换为abcd+<span color=#some-color>A6</span>
Now i want to know the current caret position. 现在我想知道当前的插入符位置。 Let say cursor is after A inside the span
, 假设光标在span
内的A之后,
but when i do 但是当我这样做
sel=window.getSelection()
pos = sel.anchorOffset
i am getting pos=1
that is the position of the caret in the span
element But i want the caret positon relative to the div
element (it should be pos=6
in this case) 我得到pos=1
,即插入符号在span
元素中的位置,但是我想要相对于div
元素的插入符号positon(在这种情况下,应该为pos=6
)
Any help would be appreciated. 任何帮助,将不胜感激。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.