在元素后设置光标 [英] Set Cursor After an element

查看:93
本文介绍了在元素后设置光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码

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

现在我将光标设置在之后将elementSpan 插入到contenteditable div中之后,而不是将光标放在 elementSpan 之后,而是放在文本之后< span class = childSpan> 内的A ,但我希望它位于 elementSpan之后

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?

推荐答案

请再次回答您的问题,这是我能找到的最接近的答案。工作。这将创建一个末尾带有& 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 &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.

我不是范围/选择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>

这篇关于在元素后设置光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆