jQuery获取光标所在的文本块

jQuery to get block of text where cursor is on

本文关键字:文本 获取 光标 jQuery      更新时间:2023-09-26

我不确定这是否可能:

单击按钮可获取光标当前所在的文本块。边界由空行确定。

例如。以下文本位于HTML代码的文本区域内

This is paragraph one
This is paragraph two and carriage return here
This is line 2 of paragraph two
Some text [cursor is here] some text
Rest of the text
This is the paragraph three

当一个按钮点击时,我想得到第二段的4行。

块的边缘在开始处和结束处由一条空行完成。

对于第一段和最后一段,只需要一行空白。

光标打开意味着鼠标点击文本区域字段中段落内的任何位置

我使用了突出显示的文本和作品。对于平板电脑来说,如果在不高亮显示的情况下也能工作,那就很方便了。

您需要使用.selectionEnd来获取插入符号位置(在旧IE中可能不支持)。。。然后用它来查找插入符号在哪个段落中。下面是一个演示:

HTML

<textarea id="source">...</textarea>
<textarea id="result"></textarea>

编写脚本

$(function() {
  var $source = $('#source'),
    $result = $('#result');
  function getParagraph() {
    var indx,
      strLength = 0,
      val = $source.val().split(/'r'r|'r'n'r'n|'n'n/),
      length = val.length,
      cursor = $source[0].selectionEnd;
    for (indx = 0; indx < length; indx++) {
      // add two more to get past the carriage returns
      strLength += val[indx].length + 2;
      if (strLength > cursor) {
        return val[indx];
      }
    }
  }
  $source.on('mouseup keyup', function() {
    $result.val(getParagraph());
  });
});