Javascript 如何将光标置于文本区域中的文本末尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6003300/
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-08-23 19:50:20  来源:igfitidea点击:

How to place cursor at end of text in textarea when tabbed into

javascripttextarea

提问by Peeter

Possible Duplicate:
Javascript: Move caret to last character

可能的重复:
Javascript:将插入符号移动到最后一个字符

I have a standard textarea with some text in it. I'm looking for a way to have the cursor automatically be placed at the end of the existing text so a user can simply start typing to add more text. This should happen whenever the textarea becomes active such as when a user tabs into it. Any ideas?

我有一个标准的 textarea,里面有一些文字。我正在寻找一种方法让光标自动放置在现有文本的末尾,以便用户可以简单地开始输入以添加更多文本。每当 textarea 变为活动状态时,例如当用户使用 Tab 键时,就会发生这种情况。有任何想法吗?

回答by Tim Down

I've answered this before: Javascript: Move caret to last character

我之前回答过这个问题:Javascript: Move caret to last character

jsFiddle: http://jsfiddle.net/ghAB9/6/

jsFiddle:http: //jsfiddle.net/ghAB9/6/

Code:

代码:

<textarea id="test">Some text</textarea>
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();
    }
}

var textarea = document.getElementById("test");

textarea.onfocus = function() {
    moveCaretToEnd(textarea);

    // Work around Chrome's little problem
    window.setTimeout(function() {
        moveCaretToEnd(textarea);
    }, 1);
};

回答by sitifensys

You need to listen to the focus event in the text area for example :

您需要在文本区域监听焦点事件,例如:

<textarea onfocus="setCursorAtTheEnd(this,event)"/>

And then in your javascript code:

然后在您的 javascript 代码中:

function setCursorAtTheEnd(aTextArea,aEvent) {
    var end=aTextArea.value.length;
    if (aTextArea.setSelectionRange) {
        setTimeout(aTextArea.setSelectionRange,0,[end,end]);  
    } else { // IE style
        var aRange = aTextArea.createTextRange();
        aRange.collapse(true);
        aRange.moveEnd('character', end);
        aRange.moveStart('character', end);
        aRange.select();    
    }
    aEvent.preventDefault();
    return false;
}