contenteditable:保存和恢复插入位置

问题描述:

下面的函数会使插入符号移回开头。在函数被调用后,我会如何让它保持在同一个位置?contenteditable:保存和恢复插入位置

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

CONTENTEDITABLE声明:

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

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

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; 
 
}
<div class="codeArea" id="writeArea" contenteditable="true"> <p> edit me! </p> </div>

+0

对不起,noob问题,但我是什么我想放弃?谷歌铬只给了我一个错误“未捕获TypeError:无法读取属性'selectionStart'未定义”。 –

+0

对contentedi div文档对象的引用 –