jQuery获取光标所在的文本块

时间:2015-12-07 05:08:46

标签: javascript jquery

我不确定这是否可行:

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

例如。以下文本位于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

点击按钮时,我想获得第2段的4行。

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

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

光标打开意味着鼠标在textarea字段中段落内的任何位置单击

我使用突出显示的文字和作品。对于平板电脑,如果没有突出显示也可以正常工作。

1 个答案:

答案 0 :(得分:1)

您需要使用.selectionEnd来获取插入位置(可能在旧IE中不受支持)...然后使用它来查找插入符号所在的段落。这是a demo

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());
  });

});