在.replace()之后恢复光标位置

Restore cursor position after .replace()

本文关键字:恢复 光标 位置 之后 replace      更新时间:2023-09-26

我最大的问题是,在它被替换后,光标默认位于文本区域的末尾。如果我在打字,这没有问题,但如果我回去编辑,这真的很烦人。这是我尝试的(textarea的id是"area")

var el = e.area;
  position = el.selectionStart; // Capture initial position
      el.value = el.value.replace(''u0418'u0410', ''u042F');
  el.selectionEnd = position;    // Set the cursor back to the initial position.

您可以尝试下面的代码片段。在当前的形式中,它将==替换为+,但它允许将任何字符串替换为另一个字符串,或短或长。

为了保持光标的位置,你必须保存和恢复selectionStartselectionEnd。计算偏移量以解释两个字符串之间的长度差异,以及在游标之前出现的次数。

使用setTimeout确保在进行处理之前将新键入的字符插入文本中。

var area = document.getElementById("area");
var getCount = function (str, search) {
    return str.split(search).length - 1;
};
var replaceText = function (search, replaceWith) {
    if (area.value.indexOf(search) >= 0) {
        var start = area.selectionStart;
        var end = area.selectionEnd;
        var textBefore = area.value.substr(0, end);
        var lengthDiff = (replaceWith.length - search.length) * getCount(textBefore, search);
        area.value = area.value.replace(search, replaceWith);
        area.selectionStart = start + lengthDiff;
        area.selectionEnd = end + lengthDiff;
    }
};
area.addEventListener("keypress", function (e) {
    setTimeout(function () {
        replaceText("==", "+");
    }, 0)
});
<textarea id="area" cols="40" rows="8"></textarea>