简体   繁体   中英

How do I preserve the caret position when changing a contenteditable div's text?

I'm trying to make a text editor that formats text based on what it says. For example, when you type "select", it changes the color of the word "select" to red. I'm using a contenteditable div .

I was able to make it change the color, but every time I change the text the caret (cursor) moves to the start of the div .

Here is my example:

 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(); }); 
 #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> 

http://jsfiddle.net/wgw8ssL6/

I am not sure if you need the answer anymore but i will answer it anyways. So the approach is to update the caret position after updating the text of the 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

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