JQUERY 将 Textarea 光标设置为文本结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13425363/
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
JQUERY Set Textarea Cursor to End of Text
提问by Adam
http://jsfiddle.net/adamadam123/gEEVM/4/
http://jsfiddle.net/adamadam123/gEEVM/4/
I'm building a chat system that allows users to add emoticons.
我正在构建一个允许用户添加表情符号的聊天系统。
Just like in the jsfiddler example above I take the current text in the textarea, combine it with the chosen emoticon symbol and then add this text back into the textarea.
就像在上面的 jsfiddler 示例中一样,我在 textarea 中获取当前文本,将其与所选的表情符号组合,然后将此文本添加回 textarea。
$(function() {
var data = $('textarea').val();
var emoticon = ':)';
$('textarea').val(data + emoticon);
$('textarea').focus();
});
The problem is when I set the focus back into the textarea the cursor is at the beginning of the text.
问题是当我将焦点设置回 textarea 时,光标位于文本的开头。
How can I set the cursor to the end of the text - to allow further typing?
如何将光标设置到文本的末尾 - 以允许进一步输入?
回答by DarkAjax
Something simple you can do is reset the text area's value:
您可以做的简单事情是重置文本区域的值:
$(function() {
var data = $('textarea').val();
var emoticon = ':)';
$('textarea').focus().val('').val(data + emoticon);
});
回答by 1.44mb
First focus, then set value. Just like this JSFiddle
先对焦,再定值。就像这个JSFiddle
$('textarea').focus();
$('textarea').val("New Text");
Another way is to add this after .focus();
另一种方法是在.focus();之后添加它。
$('textarea').val($('textarea').val() + ' ');
It adds a space to the end of the textarea thus focuses at the end.
它在 textarea 的末尾添加了一个空格,因此将焦点放在末尾。
回答by ADI
A verysimple solution.
一个非常简单的解决方案。
var emoticon = ':)';
var val = $('#textarea').val();
$('#textarea').select().val(val + emoticon);
回答by VMAtm
You should review this question:
你应该回顾一下这个问题:
jQuery Set Cursor Position in Text Area
Most elegant JQuery solution from there:
最优雅的 JQuery 解决方案:
$.fn.selectRange = function(start, end) {
return this.each(function() {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
With this, you can do
有了这个,你可以做
$('#elem').selectRange(3,5);