且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在元素后设置光标

更新时间:2022-05-07 01:04:43

请再次回答您的问题,这是我能找到的最接近的答案。工作。这将创建一个末尾带有& nbsp; 的虚拟 a ,并将光标移到它上面。 a & nbsp; 都很重要,因为没有这些浏览器( Safari,Chrome )由于某些优化,强制键入的文本进入最后一个元素。代码将光标移动到下一个元素(如果已经存在),可以通过除去 if 来删除。

Went through your question again, this is the closest I could get to work. This creates a dummy a with   at the end and moves cursor past it. Both a and   are important as without these some browsers (Safari, Chrome) force the text typed to go inside last element due to some optimisations. The code moves cursor to next element if there is one already, it can be removed by removing the if.

我不是范围/选择API的专家。期待看到其他有趣的答案。

I am not an expert in range/selection APIs. Looking forward to see other interesting answers.

elementSpan = document.createElement('span');
elementSpan.className = 'mainSpan';
document.getElementById('ce').appendChild(elementSpan);
elementSpan.innerHTML = '<span id="childSpan">Another text</span>'; //the problem am having
setCursorAfterElement(document.getElementById('childSpan'));

function setCursorAfterElement(ele) {
  if (!ele.nextElementSibling) {
    var dummyElement = document.createElement('a')
    dummyElement.appendChild(document.createTextNode('\u00A0'))
    ele.parentNode.appendChild(dummyElement)
  }
  var nextElement = ele.nextElementSibling
  nextElement.tabIndex=0
  nextElement.focus()
  var r = document.createRange();
  r.setStart(nextElement.childNodes[0], 1);
  r.setEnd(nextElement.childNodes[0], 1);

  var s = window.getSelection();
  s.removeAllRanges();
  s.addRange(r);
  //document.execCommand("delete", false, null);
}

#childSpan {
  border: 1px solid red;
  margin: 0px;
}

<div id="ce" contenteditable="true">
</div>