2017-09-17 170 views
0

下面的函數會使插入符號移回開頭。在函數被調用後,我會如何讓它保持在同一個位置?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> 

回答

0

使用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文檔對象的引用 –

相關問題