如何在文本区域中的末尾设置光标

How to set cursor at the end in a textarea?

本文关键字:置光标 文本 区域      更新时间:2023-09-26

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

没有框架或库。

可能有很多方法,例如

element.focus();
element.setSelectionRange(element.value.length,element.value.length);

http://jsfiddle.net/doktormolle/GSwfW/

selectionStart 足以设置初始光标点。

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

我已经很久没有先看 jQuery 解决方案就使用 javascript 了......

话虽如此,使用 javascript 的最佳方法是在文本区域中当前处于焦点时获取值,并将文本区域的值设置为抓取的值。这在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;
}

我可能是错的。有点生锈。

var t = /* get textbox element */ ;
t.onfocus = function () { 
    t.scrollTop = t.scrollHeight; 
    setTimeout(function(){ 
      t.select(); 
      t.selectionStart = t.selectionEnd; 
    }, 10); 
}

诀窍是在浏览器处理完焦点事件后使用 setTimeout 更改文本插入(克拉)位置;否则位置将由我们的脚本设置,然后立即由浏览器设置为其他位置。

这是一个函数

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

演示][来源]

textarea.focus()
textarea.value+=' ';//adds a space at the end, scrolls it into view
(this.jQuery || this.Zepto).fn.focusEnd = function () {
    return this.each(function () {
        var val = this.value;
        this.focus();
        this.value = '';
        this.value = val;
    });
};

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