问题
this happens in chrome (71.0.3578.80 on windows):
on range.setStart the caret moves to the reference node, but after typing the new characters appear in the node before, when offset is 0.
the expected behaviour would be, that the characters appear in the reference node of range.setStart.
see here:
http://jsfiddle.net/pgrds9qv/
function setCaret() {
var el = document.getElementById("editable");
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el.childNodes[2], 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
div {
padding: 10px;
}
span {
border: 1px solid black;
font-size: 120%;
padding: 5px;
}
<div id="editable" contenteditable="true">
<span>first </span><span>second </span><span>third </span>
</div>
<div>
<button id="button" onclick="setCaret()">focus</button>
</div>
in firefox it works fine. how to get the same behaviour in chrome? or is there an alternative way of achieving this? thanks a lot for any hints!
来源:https://stackoverflow.com/questions/53747581/after-range-setstart-new-characters-appear-in-previous-node