如何在文本区域中将光标设置到末尾?

28
有没有一种方法可以在 textarea 元素中将光标设置在末尾?我使用的是 Firefox 3.6,不需要在 IE 或 Chrome 中工作。这里所有相关的答案似乎都使用了 onfocus() 事件,但这似乎是无用的,因为当用户在 textarea 元素内任意点击时,Firefox 会将光标位置设置到那里。我有一个长文本要显示在 textarea 中,以使它显示最后一部分(以便更容易地在末尾添加内容)。没有任何框架或库。
8个回答

52

13

使用 selectionStart 就足以设置初始光标位置。

    element.focus();
    element.selectionStart = element.value.length;

5

我很久没有使用纯javascript而不是首先看jQuery的解决方案了...

话虽如此,你最好使用javascript的方法是在textarea获得焦点时获取当前值,并将textarea的值设置为获取到的值。在jQuery中,这始终有效,例如:

$('textarea').focus(function() {
    var theVal = $(this).val();
    $(this).val(theVal);
});

使用普通的JavaScript:

var theArea = document.getElementByName('[textareaname]');

theArea.onFocus = function(){
    var theVal = theArea.value;
    theArea.value = theVal;
}

我可能错了,有点生疏。


我喜欢这个解决方案,因为它只有两行代码,但我认为它比Starx的解决方案更费力。 - David 天宇 Wong

3
var t = /* get textbox element */ ;

t.onfocus = function () { 
    t.scrollTop = t.scrollHeight; 
    setTimeout(function(){ 
      t.select(); 
      t.selectionStart = t.selectionEnd; 
    }, 10); 
}
是使用setTimeout在浏览器处理焦点事件完成更改文本插入(插入符)位置的技巧;否则,位置将由我们的脚本设置,然后立即由浏览器设置为其他内容。

3
这里有一个相应的函数:
function moveCaretToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

[Demo][Source]


2
textarea.focus()
textarea.value+=' ';//adds a space at the end, scrolls it into view

1
(this.jQuery || this.Zepto).fn.focusEnd = function () {
    return this.each(function () {
        var val = this.value;
        this.focus();
        this.value = '';
        this.value = val;
    });
};

0

@Dr.Molle的回答是正确的。只是为了增强,您可以与prevent-default结合使用。

http://jsfiddle.net/70des6y2/

示例:

document.getElementById("textarea").addEventListener("mousedown", e => {
  e.preventDefault();
  moveToEnd(e.target);
});
function moveToEnd(element) {
  element.focus();
  element.setSelectionRange(element.value.length, element.value.length);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接