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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top