javascript contenteditable: set cursor at characte

2019-08-29 04:42发布

问题:

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.