使用JQuery提取文本区域中的光标位置和突出显示的文本 [英] Fetching cursor location and highlighted text in textarea using JQuery
问题描述
以某种形式具有文本区域,我正在尝试做几件事:
Having a textarea in a form I am trying to do several things:
- 获取光标在文本区域内的当前位置
- 在文本区域中获取当前选择
- 在当前光标位置插入一些文本
- 用其他一些文字代替当前选择
由于我已经在使用JQuery,所以我希望有一个与此兼容的解决方案. 任何达到上述目的的指针将不胜感激.
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.
推荐答案
有很多jQuery插件.这是我以前用过的好东西:
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();
这将返回如下对象:
{
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');
这篇关于使用JQuery提取文本区域中的光标位置和突出显示的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!