javascript 更新 textarea 值,但保持光标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3286595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:45:14  来源:igfitidea点击:

update textarea value, but keep cursor position

javascripthtml

提问by Ben Noland

I have an html textarea that will be updated periodically via javascript.

我有一个 html textarea,它将通过 javascript 定期更新。

when I do this:

当我这样做时:

$("#textarea").val(new_val);

The cursor moves to the end of the text.

光标移动到文本的末尾。

I would like to update the text without changing the cursor position. Also, if the user has a range of text selected, the highlight should be preserved.

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

回答by Tim Down

Here is a pair of functions that get and set the selection/caret position in a text area in all major browsers.

这是在所有主要浏览器的文本区域中获取和设置选择/插入符号位置的一对函数。

Note: if you don't need to support IE <= 8, just use the selectionStartand selectionEndproperties (MDN). All of the complicated code below is just there to support old versions of IE.

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

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();
    }
}

When you change the textarea's value, first save the selection, then restore it afterwards:

当您更改 textarea 的值时,首先保存选择,然后再恢复它:

var t = document.getElementById("textarea");
var sel = getInputSelection(t);
t.value = some_new_value;
setInputSelection(t, sel.start, sel.end);