在.replace()之后恢复光标位置 [英] Restore cursor position after .replace()
问题描述
我最大的问题是,替换后,光标默认为文本区域的末尾.如果我要键入那没问题,但是如果我要返回并进行编辑,那确实很烦人.这是我尝试过的(textarea的ID为"area")
My biggest problem is that after it's replaced, the cursor defaults to the end of the textarea. That's no issue if I'm typing, but if I'm going back and editing, it's really annoying. Here's what I tried (the id of the textarea is "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.
推荐答案
您可以尝试以下代码段.以其当前形式,它将 ==
替换为 +
,但是它允许将任何字符串替换为另一个(更短或更长时间).
You can try the following code snippet. In its current form, it replaces ==
with +
, but it allows to replace any string with another one, shorter or longer.
为了保持光标位置,您必须保存并恢复 selectionStart
和 selectionEnd
.计算偏移量是为了考虑两个字符串之间的长度差异以及光标之前出现的次数.
In order to maintain the cursor position, you have to save and restore the selectionStart
and the selectionEnd
. An offset is calculated to account for the difference in length between the two strings, and the number of occurrences before the cursor.
使用 setTimeout
可以确保在执行处理之前已在文本中插入了新键入的字符.
The use of setTimeout
ensures that the newly typed character has been inserted in the text before doing the processing.
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>
这篇关于在.replace()之后恢复光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!