Fetching cursor location and highlighted text in textarea using JQuery

大憨熊 提交于 2019-12-11 13:03:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!