简体   繁体   中英

contenteditable: save and restore caret position

The function below causes the caret to move back to the beginning. How would I make it stay at the same spot after the function is called?

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

Contenteditable declaration:

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

Use selectionStart to get and set the position of the caret:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM