contenteditable:保存和恢复插入位置

时间:2017-09-17 01:41:53

标签: javascript jquery html contenteditable caret

以下功能会使插入符号移回到开头。在调用函数后,如何使它保持在同一位置?

function highlightText() {
            var mystring = document.getElementById("writeArea").textContent;
            mystring = mystring.replace(/function/g , "<span class=\"func\">function</span>");
            document.getElementById("writeArea").innerHTML = mystring;
        }

可信的声明:

<div class="codeArea" id="writeArea" contenteditable="true"> <p> edit me! </p> </div>

1 个答案:

答案 0 :(得分:0)

使用selectionStart来获取和设置插入符号的位置:

&#13;
&#13;
document.getElementById("writeArea").onkeyup = highlightText(this);
function highlightText(o) {
  var mystring = document.getElementById("writeArea").textContent,
  caretPosition = o.selectionStart;
  mystring = mystring.replace(/function/g , "<span class=\"func\">function</span>");
  document.getElementById("writeArea").innerHTML = mystring;
  document.getElementById("writeArea").selectionStart = caretPosition;
}
&#13;
<div class="codeArea" id="writeArea" contenteditable="true"> <p> edit me! </p> </div>
&#13;
&#13;
&#13;