使用JQuery在文本区获取光标位置和高亮显示的文本

Fetching cursor location and highlighted text in textarea using JQuery

本文关键字:高亮 显示 文本 位置 光标 JQuery 文本区 获取 使用      更新时间:2023-09-26

在表单中有一个文本区,我想做几件事:

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

因为我已经在使用JQuery,我更喜欢一个解决方案,工作顺利。如能指点如何实现上述目标,我将不胜感激。

有很多jQuery插件。这是我以前用过的一个很好的例子:

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


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

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

获取文本区域内的当前选择:

$("textarea").getSelection();

this返回如下对象:

{
    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');