javascript - Getting the Correct Position of a Selected Text in a Div -
i have requirement have find position of selected text within content-editable div. 1 time select word of text, highlight surrounding word span css in it. starting position of highlighted word.
the problem if have highlighted word @ index 0 , after seek select/highlight word illustration @ index 10 of div, position wrong.
here image reference:
see how highlighted word "position" beingness reported me beingness on index 1, when should 8.
here code pick position of selected text:
var sel, range; if (window.getselection) { sel = window.getselection(); if (sel.rangecount) { range = sel.getrangeat(0).clonerange(); homecoming range.startoffset; } } else { homecoming null; } i appreciate help on this. thanks
when select within contenteditable div, getselection() returns selection object anchornode type of "text". is, you're selecting text node of containing div. when div looks this:
<div contenteditable="true">testing position of preview</div> the text node kid node of div.
however, 1 time create selection , mark span:
<div contenteditable="true"><span class="marked">testing</span> position of preview</div> you have three descendant nodes of div: span, text node within span, , text node within div. therefore, when range of selection object returned after selecting word "position", returning range relative div's text node, has contents of
" position of preview" (note space before word "position").
so, offset of "position" 1 origin of anchor node, reported.
javascript jquery html css
No comments:
Post a Comment