将值插入到游标所在的TEXTAREA中 [英] Insert value into TEXTAREA where cursor was
问题描述
我有一个textarea和一个带有值的div。当我点击一个值时,我将其插入textarea。我需要将它插入我的光标在textarea中的位置。为什么我说WAS?因为当我将其移出并单击要插入的值时,我认为它在文本区域中失去焦点。
I have a textarea and a div with values. When I click on a value I insert it into textarea. I need it to be inserted where my cursor was in textarea. Why do I say WAS? Because when I move it out and click on a value to insert, I assume it looses focus in the text area.
所以,我的问题是,有没有办法记住textarea中的最新光标位置,然后在那个位置插入我的值?
So, my question is, is there a way to "remember" the latest cursor position within textarea and then insert my values at that position?
也许它可能是字符串中的字符编号?..目前我这样添加:
Perhaps it could be a char number in a string?.. Currently I add it like this:
input.val( function( i, val ) { return val + " " + myInsert + " "; } );
我也使用jQuery,也许我可以使用它?
Also I use jQuery, perhaps I could use it?
推荐答案
我编写了一个跨浏览器的jQuery插件,用于处理textareas和文本输入中的插入/选择,称为 Rangy输入(可怕的名字,我真的应该想到更好的一个)。这里的方法和 Edgar Villegas Alvarado的回答中的技术相结合应该这样做,虽然在IE中,焦点
事件触发太晚,你需要使用专有的才能激活
事件代替:
I've written a cross-browser jQuery plug-in for dealing with the caret/selection in textareas and text inputs called Rangy inputs (terrible name, I really should think of a better one). A combination of methods from this and the techniques in Edgar Villegas Alvarado's answer should do the trick, although in IE, the focusout
event fires too late and you'll need to use the proprietary beforedeactivate
event instead:
var $textBox = $("#foo");
function saveSelection(){
$textBox.data("lastSelection", $textBox.getSelection());
}
$textBox.focusout(saveSelection);
$textBox.bind("beforedeactivate", function() {
saveSelection();
$textBox.unbind("focusout");
});
稍后插入文本时,以下内容将在前一个光标位置插入文本(或覆盖之前选择的文本)文本,如果用户选择了任何):
When inserting text later, the following will insert text at the previous cursor position (or overwrite the previously selected text, if the user had selected any):
var selection = $textBox.data("lastSelection");
$textBox.focus();
$textBox.setSelection(selection.start, selection.end);
$textBox.replaceSelectedText("Some new text");
请参阅此处的jsFiddle示例: http://jsfiddle.net/rQXrJ/1/
See jsFiddle example here: http://jsfiddle.net/rQXrJ/1/
这篇关于将值插入到游标所在的TEXTAREA中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!