javascript contenteditable: set cursor at character offset

笑着哭i 提交于 2019-12-23 04:07:11

问题


I need to set the cursor at a specific character offset. In the example below, I'd want to, for example, set it between the "a" and the "b".

<ul contenteditable = true >
    <li id = "test">abcdef</li>
</ul>

I asked before and got this fiddle: http://jsfiddle.net/5a9uD/1/

That worked great for the given example and for what I needed it for then. But it does not work with this example: http://jsfiddle.net/mdwWN/ It gets an IndexSizeError at

range   = sel.getRangeAt(0);

回答1:


You just have to pass text container's childNodes[0] to range.setStart function. Check this out.

function setSelectionRange(aNode, childElem, aOffset) {

  aNode.focus();

  var sel = window.getSelection(),
  range = sel.getRangeAt(0);

  range.collapse(true);

  range.setStart(childElem.childNodes[0], aOffset),

  sel.removeAllRanges();
  sel.addRange(range);
}

var container = document.getElementById("test");
var childElement = document.getElementById('item1');
setSelectionRange(container, childElement, 1);

Here is the working fiddle.



来源:https://stackoverflow.com/questions/17358651/javascript-contenteditable-set-cursor-at-character-offset

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