我有一个简单的HTML作为例子:

<div id="editable" contenteditable="true">
  text text text<br>
  text text text<br>
  text text text<br>
</div>
<button id="button">focus</button>

我想要简单的东西-当我点击按钮时,我想在可编辑的div中放置插入符号(光标)到特定的地方。从网上搜索,我有这个JS附加到按钮点击,但它不起作用(FF, Chrome):

const range = document.createRange();
const myDiv = document.getElementById("editable");
range.setStart(myDiv, 5);
range.setEnd(myDiv, 5);

是否可以像这样手动设置插入符号的位置?


当前回答

我已经阅读并尝试了这里的一些案例,只是把对我有用的放在这里,根据dom节点考虑一些细节:

  focus(textInput){
    const length = textInput.innerText.length;
    textInput.focus();

    if(!!textInput.lastChild){
      const sel = window.getSelection();
      sel.collapse(textInput.lastChild, length);
    }
  }

其他回答

基于Tim Down的答案,但它会检查最后一个已知的“好”文本行。它把光标放在最后。

此外,我还可以递归/迭代地检查每个连续的最后一个子节点的最后一个子节点,以找到DOM中绝对最后一个“好”文本节点。

function onClickHandler() { setCaret(document.getElementById("editable")); } function setCaret(el) { let range = document.createRange(), sel = window.getSelection(), lastKnownIndex = -1; for (let i = 0; i < el.childNodes.length; i++) { if (isTextNodeAndContentNoEmpty(el.childNodes[i])) { lastKnownIndex = i; } } if (lastKnownIndex === -1) { throw new Error('Could not find valid text content'); } let row = el.childNodes[lastKnownIndex], col = row.textContent.length; range.setStart(row, col); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); el.focus(); } function isTextNodeAndContentNoEmpty(node) { return node.nodeType == Node.TEXT_NODE && node.textContent.trim().length > 0 } <div id="editable" contenteditable="true"> text text text<br>text text text<br>text text text<br> </div> <button id="button" onclick="onClickHandler()">focus</button>

我正在编写一个语法高亮显示(和基本的代码编辑器),我需要知道如何自动键入一个单引号字符并将插入符号移回(就像现在的许多代码编辑器一样)。

这里是我的解决方案的一个片段,感谢来自这个线程的帮助,MDN文档,和很多moz控制台观看。

//onKeyPress event

if (evt.key === "\"") {
    let sel = window.getSelection();
    let offset = sel.focusOffset;
    let focus = sel.focusNode;

    focus.textContent += "\""; //setting div's innerText directly creates new
    //nodes, which invalidate our selections, so we modify the focusNode directly

    let range = document.createRange();
    range.selectNode(focus);
    range.setStart(focus, offset);

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

//end onKeyPress event

这是一个可满足内容的div元素

我把这个留在这里作为感谢,意识到已经有一个公认的答案。

在大多数浏览器中,都需要Range和Selection对象。将每个选择边界指定为一个节点,并在该节点中指定偏移量。例如,要将插入符号设置为第二行文本的第五个字符,您可以执行以下操作:

function setCaret() var el =文档。getElementById(“编辑”) 咖啡壶。 var = window.getSelection() 太阳城setStart (el。childNodes [2], 5) 太阳城崩溃(真正的)。 细胞removeAllRanges()。 细胞addRange(射程)。 的 <div id=“编辑”contenteble =“真”> 文本文本<br>文本文本<br>文本文本<br> < / div > <巴顿id=“巴顿”onclick=“setCaret”()巴顿”focus > < - >

IE < 9的工作方式完全不同。如果需要支持这些浏览器,则需要不同的代码。

jsFiddle示例:http://jsfiddle.net/timdown/vXnCM/

我已经阅读并尝试了这里的一些案例,只是把对我有用的放在这里,根据dom节点考虑一些细节:

  focus(textInput){
    const length = textInput.innerText.length;
    textInput.focus();

    if(!!textInput.lastChild){
      const sel = window.getSelection();
      sel.collapse(textInput.lastChild, length);
    }
  }
  const el = document.getElementById("editable");
  el.focus()
  let char = 1, sel; // character at which to place caret

  if (document.selection) {
    sel = document.selection.createRange();
    sel.moveStart('character', char);
    sel.select();
  }
  else {
    sel = window.getSelection();
    sel.collapse(el.lastChild, char);
  }