以下功能会使插入符号移回到开头。在调用函数后,如何使它保持在同一位置?
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>
答案 0 :(得分: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;
}
&#13;
<div class="codeArea" id="writeArea" contenteditable="true"> <p> edit me! </p> </div>
&#13;