Set Cursor After an element

末鹿安然 提交于 2020-01-05 05:19:21

问题


I have this code

elementSpan = document.createElement('span').className = 'mainSpan';
elementSpan.innerHTML = '<span class="childSpan">A</sapn>';
range.insertNode(elementSpan);
range.setStartAfter(elementSpan);  //the problem am having

Now I set the cursor to be after the elementSpan after inserting it into a contenteditable div but instead of the cursor to be after the elementSpan, it goes after the text A which is inside the <span class="childSpan"> but I want it to be after the elementSpan. Please anyone with a clue on how to do this?


回答1:


Went through your question again, this is the closest I could get to work. This creates a dummy a with &nbsp; at the end and moves cursor past it. Both a and &nbsp; 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.

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>


来源:https://stackoverflow.com/questions/41076588/set-cursor-after-an-element

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