首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新文本区域值,但保持光标位置不变

问更新文本区域值,但保持光标位置不变
EN

Stack Overflow用户
提问于 2010-07-20 10:37:36
回答 2查看 15.1K关注 0票数 17

我有一个html文本区域,将通过javascript定期更新。

当我这样做的时候:

代码语言:javascript
复制
$("#textarea").val(new_val);

光标移动到文本的末尾。

我想在不改变光标位置的情况下更新文本。此外,如果用户选择了一定范围的文本,则应保留突出显示。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-07-20 16:33:45

下面这两个函数可以在所有主流浏览器中获取和设置文本区域中的选择/插入符号位置。

注意:如果不需要支持IE <= 8,只需使用selectionStart和selectionEnd属性(MDN)即可。下面所有复杂的代码都只是为了支持旧版本的IE。

代码语言:javascript
复制
function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

function offsetToRangeCharacterMove(el, offset) {
    return offset - (el.value.slice(0, offset).split("\r\n").length - 1);
}

function setInputSelection(el, startOffset, endOffset) {
    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        el.selectionStart = startOffset;
        el.selectionEnd = endOffset;
    } else {
        var range = el.createTextRange();
        var startCharMove = offsetToRangeCharacterMove(el, startOffset);
        range.collapse(true);
        if (startOffset == endOffset) {
            range.move("character", startCharMove);
        } else {
            range.moveEnd("character", offsetToRangeCharacterMove(el, endOffset));
            range.moveStart("character", startCharMove);
        }
        range.select();
    }
}

当你改变文本区域的值时,首先保存选择,然后恢复它:

代码语言:javascript
复制
var t = document.getElementById("textarea");
var sel = getInputSelection(t);
t.value = some_new_value;
setInputSelection(t, sel.start, sel.end);
票数 23
EN

Stack Overflow用户

发布于 2021-02-26 18:24:36

十年后,但这是我想出的在文本区域中替换项目的方法。当用更长或更短的文本替换时,需要一些额外的处理来调整插入符号或选择。

​

代码语言:javascript
复制
// find and replace in textarea while preserving caret and selection
function replaceText(el, findText, replaceWithText) {
    var text = el.value;
    var selectionStart = 0;
    var selectionEnd = 0;
  // only support modern browsers for preserving caret and selection
    if (el.setSelectionRange) {
        selectionStart = el.selectionStart;
        selectionEnd = el.selectionEnd;
    }
    var start = 0;
    while ((start = text.indexOf(findText, start)) > -1) {
        var end = start + findText.length;
        text = text.substr(0, start) + replaceWithText + text.substr(end);
        if (selectionStart < end) {
            selectionStart = Math.min(selectionStart, start + replaceWithText.length);
        } else {
            selectionStart = selectionStart + replaceWithText.length - (end - start);
        }
        if (selectionEnd < end) {
            selectionEnd = Math.min(selectionEnd, start + replaceWithText.length);
        } else {
            selectionEnd = selectionEnd + replaceWithText.length - (end - start);
        }
        start += replaceWithText.length;
    }
  // don't do anything unless we need to (otherwise destroys undo)
    if (el.value != text) { 
        el.value = text;
        if (el.setSelectionRange) {
            el.selectionStart = selectionStart;
            el.selectionEnd = selectionEnd;
        }
    }
}
代码语言:javascript
复制
Place caret on or after the word LONGER, or select some text after or including it:
<br />
<textarea id='t'>Here is
some LONGERtext
to replace</textarea>
<br />
<input type="button" onclick="replaceText(document.getElementById('t'),'LONGER',''); document.getElementById('t').focus();" value="remove word LONGER" />

​

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3286595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档