使用JQuery在textarea中获取光标位置和突出显示的文本

在表格中有一个textarea我试图做几件事:

  • 获取文本区域内光标的当前位置
  • 获取textarea中的当前选择
  • 在当前光标位置插入一些文本
  • 用其他文字替换当前选择

由于我已经在使用JQuery,我更喜欢一种能够顺利运行的解决方案。 任何指针如何实现上述将是值得赞赏的。

这有很多jQuery插件。 这是我以前用过的好文章:

http://plugins.jquery.com/project/a-tools


要在文本区域内获取光标的当前位置:

$("textarea").getSelection().start; 

要获取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' } 

要在当前光标位置插入一些文本:

 $("#textarea").insertAtCaretPos("The text to insert"); 

要通过其他文本替换当前选择:

 $("#textarea").replaceSelection('This text will replace the selection');