![](/img/trans.png)
[英]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.