更新输入值时如何保持光标位置

How to maintain cursor position when updating input value

我正在 "Add comment box" 开发一些功能,例如将 [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;
    }
});

您是否尝试过将焦点放回到该元素上?通常,浏览器(IE 除外)一旦将光标带回 focus.Since 您正在使用 jquery:

,就会将光标放回原来的位置

$("#yourID").focus()

我认为你应该使用 lexter/parser 来将 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>