2015-11-30 50 views
0

我正在處理「添加評論框」,其中包含一些功能,如將[b]text[/b]更改爲帶粗體樣式的文本等。問題是當javascript中的str.replace操作完成了寫入區域中的光標回到開始位置時。如何在更新輸入值時保持光標位置

$('#comment').keyup(function() { 
    var str = document.getElementById("comment").innerHTML; 
    if (str.indexOf('[b]') >= 0 && str.indexOf('[/b]') >= 0) { 
     var start_pos = str.indexOf('[b]') + 3; 
     var end_pos = str.indexOf('[/b]', start_pos); 
     var text_to_get = str.substring(start_pos, end_pos) 
     res = str.replace("[b]" + text_to_get + "[/b]", "<b>" + text_to_get + "</b>"); 
     document.getElementById("comment").innerHTML = res; 
    } 
}); 
+2

這不是關於'str.replace'的問題,而是'innerHTML'的行爲。 – isherwood

+0

[這個問題和答案](http://stackoverflow.com/questions/7745867/how-do-you-get-the-cursor-position-in-a-textarea)有幫助嗎? – Blazemonger

+0

[在contenteditable div中保持遊標位置]的可能重複(http://stackoverflow.com/questions/16194364/maintain-cursor-position-in-contenteditable-div) – isherwood

回答

0

我認爲你應該使用一個lexter /解析器,而不是將bbcode轉換爲HTML(除非原因是您希望通過這樣做來學習)。

Here's one that might work for you。它支持默認的bbcode塊,並可以定義你自己的。

<head> 
    <!-- Optional styling for .xbbcode-* classes --> 
    <link rel="stylesheet" type="text/css" href="xbbcode.css"> 
</head> 
<body> 
    <script src="xbbcode.js"></script> 
    <script> 
    var text = document.getElementById("comment").innerHTML; 
    var result = XBBCODE.process({ 
     text: text, 
     removeMisalignedTags: false, 
     addInLineBreaks: false 
    }); 
    console.error("Errors", result.error); 
    console.dir(result.errorQueue); 
    console.log(result.html); //=> <span class="xbbcode-b">Hello world</span> 
    </script> 
</body> 
0

您是否嘗試將焦點放回元素上?通常情況下,瀏覽器(IE除外),把光標返回到它`原來的位置,一旦它被帶回focus.Since你正在使用jQuery:

$("#yourID").focus()

相關問題