Javascript jQuery获取光标所在的文本块

Javascript jQuery获取光标所在的文本块,javascript,jquery,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 当一个按钮点击

我不确定这是否可行:

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

下面的文本位于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行

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

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

光标位于表示鼠标在textarea字段中段落内的任意位置单击


我使用了突出显示的文本和作品。对于平板电脑,如果在未突出显示的情况下也能工作,则非常方便。

您需要使用
。选择“结束”
以获得插入符号位置(旧版IE可能不支持)。。。然后使用它找到插入符号所在的段落。这是:

HTML

。。。
剧本

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

});
$(函数(){
var$source=$(“#source”),
$result=$(“#result”);
函数get段落(){
var indx,
strLength=0,
val=$source.val().split(/\r\r |\r\n\r\n |\n\n/),
长度=val.length,
游标=$source[0]。选择结束;
对于(indx=0;indx光标){
返回值[indx];
}
}
}
$source.on('mouseup keyup',function(){
$result.val(get段落());
});
});

向我们展示您的HTML代码,然后是您尝试过的脚本?嗨,John,我已经用更多细节更新了问题谢谢。我不介意IE,因为手机/平板电脑中没有IE
$(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());
  });

});