问题
Having a textarea in a form I am trying to do several things:
- fetch the current location of the cursor within the text area
- fetch the current selection within the textarea
- insert some text at the current cursor location
- replace the current selection by some other text
As I am already using JQuery, I'd prefer a solution that works smoothly with that. Any pointers how to achieve the above would be appreciated.
回答1:
There are many jQuery plugins for this. Here's a good one I've used before:
http://plugins.jquery.com/project/a-tools
To fetch the current location of the cursor within the text area:
$("textarea").getSelection().start;
To fetch the current selection within the textarea:
$("textarea").getSelection();
this returns an object like this:
{
start: 1, // where the selection starts
end: 4, // where the selection ends
length: 3, // the length of the selection
text: 'The selected text'
}
To insert some text at the current cursor location:
$("#textarea").insertAtCaretPos("The text to insert");
To replace the current selection by some other text:
$("#textarea").replaceSelection('This text will replace the selection');
来源:https://stackoverflow.com/questions/7625011/fetching-cursor-location-and-highlighted-text-in-textarea-using-jquery