2015-12-07 21 views
1

我不確定這是否可能: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場

我用突出顯示的文本和作品段落的任何地方。對於平板電腦,如果在沒有突出顯示的情況下也可以正常工作,這很方便

+3

向我們展示你的HTML代碼,然後腳本你已經嘗試了什麼? –

+0

嗨,約翰,我更新了更多的細節 – SIDU

回答

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

}); 
+0

感謝工作。我不介意IE。由於手機/平板電腦中沒有IE – SIDU