在更改可疑的div文本时,如何保留插入位置?

时间:2015-10-21 17:33:40

标签: javascript html contenteditable caret getcaretpos

我试图制作一个文本编辑器,根据文字说明格式化文本。例如,当您键入"选择"时,它会更改单词的颜色"选择"变红了。我使用contenteditable div

我能够改变颜色,但每次更改文本时,插入符号(光标)都会移动到div的开头。

以下是我的例子:



var replace = function(text, q, r){
  text=text.split(q);
  var result = text[0];
  for(var i = 1; i < text.length; i++){
    result += r + text[i];
  }
  return result;
};

var run = function(){
  document.getElementById('code_editor').innerHTML
  = replace(document.getElementById('code_editor').textContent, "select", "<span class='start'>select</span>"); 
}
$('#code_editor').keyup(function (event) {
  run();
});
&#13;
#code_editor {
  width: 600px;
  height: 100px;
  box-shadow: inset 0px 0px 2px black;
  padding: 5px;
  overflow-y: scroll;
}
.start {
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code><div id="code_editor" contenteditable tabindex="1"></div></code>
&#13;
&#13;
&#13;

http://jsfiddle.net/wgw8ssL6/

1 个答案:

答案 0 :(得分:0)

我不确定你是否还需要答案,但无论如何我都会回答。因此,方法是在更新div的文本后更新插入位置。

var replace = function(text, q, r){
  text=text.split(q);
  var result = text[0];
  for(var i = 1; i < text.length; i++){
    result += r + text[i];
  }
  return result;
};

var run = function(){
  document.getElementById('code_editor').innerHTML
  = replace(document.getElementById('code_editor').textContent, "select", "<span class='start'>select</span>"); 
placeCaretAtEnd(document.getElementById('code_editor')); //Function invoke
}
/*Function to place caret at end*/
function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
    console.log("[placeCaretAtEnd updated]");
}
$('#code_editor').keyup(function (event) {
  run();
});
#code_editor {
  width: 600px;
  height: 100px;
  box-shadow: inset 0px 0px 2px black;
  padding: 5px;
  overflow-y: scroll;
}
.start {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code><div id="code_editor" contenteditable tabindex="1"></div></code>

Credits for the function