[英]Contenteditable div: save and restore caret position when is positioned in empty new line
[英]contenteditable: save and restore caret position
下面的功能使插入符號移回到起點。 調用函數后,如何使它停留在同一位置?
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>
使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.