2015-10-21 69 views
3

我正在嘗試使文本編輯器基於它所說的格式來設置文本。例如,當您鍵入「select」時,它將單詞「select」的顏色更改爲紅色。我正在使用contenteditablediv如何在更改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(); 
 
});
#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/

回答

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

相關問題