2015-11-30 53 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()

相关问题