Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

javascript - Insert value into TEXTAREA where cursor 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.

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

Also I use jQuery, perhaps I could use it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

See jsFiddle example here: http://jsfiddle.net/rQXrJ/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...