简体   繁体   中英

How to set cursor position in contenteditable span

I have a span, it becomes editable after double clicking on it. However, some text is selected due to double click and I remove that selection using this code:

function removeSelectedText(element) {
if (window.getSelection || document.getSelection) {
    oSelection = (window.getSelection ? window:document).getSelection();
    oSelection.removeAllRanges();
} else {
    document.selection.empty();
}
}

After this operation, now-editable non-selected span loses focus. All I want to move the caret to the last clicked place in the span. I try the code below but didn't work ('element' is span itself):

...
var selection = (window.getSelection ? window:document).getSelection();
var position = selection.getRangeAt(0).focusOffset;
element.focus();

var range = document.createRange();
range.setStart(element, position);
range.setEnd(element, position);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);

I try whatever I found but couldn't get it working. I can't focus it anymore due to frustration. That would be awesome if you help me...

UPDATE: In range.setStart() and range.setEnd() , element.firstChild should be used instead of element .

A similar problem and its solution is here , I am surprised for finding it in the second day of search considering my offensive search yesterday. Any better solution is welcomed, since even this one cannot bypass text selection at first double click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM