选中时如何将光标放在textarea中的文本末尾 [英] How to place cursor at end of text in textarea when tabbed into

查看:433
本文介绍了选中时如何将光标放在textarea中的文本末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Javascript:将插入符号移到最后一个字符

I有一个标准的textarea,里面有一些文字。我正在寻找一种方法让光标自动放在现有文本的末尾,这样用户就可以简单地开始输入以添加更多文本。每当textarea变为活动状态时(例如当用户选中它时)就会发生这种情况。有什么想法?

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?

推荐答案

我之前已经回答过: Javascript:将插入符号移到最后一个字符

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

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

代码:

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

这篇关于选中时如何将光标放在textarea中的文本末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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