after range.setStart new characters appear in previous node

浪子不回头ぞ 提交于 2021-02-08 08:21:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!