更新textarea值,但保持光标位置 [英] update textarea value, but keep cursor position

查看:230
本文介绍了更新textarea值,但保持光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



<$>



<$>我有一个html textarea,它会通过javascript定期更新。 p $ p> $( #textarea的)VAL(new_val)。

光标移动到文本的末尾。



我想在不更改光标位置的情况下更新文本。此外,如果用户选择了一定范围的文本,应该保留高亮。

解决方案

这是一对功能,在所有主流浏览器的文本区域中获取并设置选择/插入位置。

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

 函数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\\\
/ g,\\\
);

//创建一个只工作在输入中的TextRange
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());

//检查选择的开始和结束是否在输入的最后
//,因为moveStart / moveEnd不会返回我们想要的
/ /在这些情况下
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(\\\
)。length - 1;

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

返回{
开始:开始,
结束:结束
} ;
}

函数offsetToRangeCharacterMove(el,offset){
返回偏移量 - (el.value.slice(0,offset).split(\r\\\
).length - 1);
}

函数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();


$ / code>

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

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


I have an html textarea that will be updated periodically via 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.

解决方案

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 selectionStart and selectionEnd properties (MDN). All of the complicated code below is just there to support old versions of 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:

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

这篇关于更新textarea值,但保持光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆