2012-09-23 61 views
23

可能重複:
Find out the 'line' (row) number of the cursor in a textarea獲取行號在文本區域

我想找出的行號,一個用戶的光標在一個HTML元素textarea

這是可能使用JavaScript和jQuery?

+1

定義在一個文本行。它包含包裝文本還是隻想考慮換行符? – zeebonk

+0

我想在一行中設置15個字符限制,並且用戶不應該能夠在5行中輸入超過75個字符 – Freelancer

+0

尼斯問題真的:)喜歡和書籤;) – Marwan

回答

20

這適用於按鈕單擊。從Find out the 'line' (row) number of the cursor in a textarea

​function getline() 
{ 
    var t = $("#t")[0]; 
    alert(t.value.substr(0, t.selectionStart).split("\n").length); 
}​ 

HTML被盜

​<textarea rows="6" id="t"> 
there is no 
love in the ghetto 
so come here 
and get it 
</textarea> 
<input type="button" onclick="getline()" value="get line" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 
+3

這不包含由換行引起的換行符。 –

+4

@RobW:我不認爲OP需要那 – Bergi

+0

它對我有效...它的幫助 – Freelancer

1

您可以用下面的辦法

  1. Find the caret positio N(指數)。
  2. 搜索由位置0的子索引
  3. 搜索的步驟中獲得的子串中的新線路號2.

//測試

$(function() { 
    $('#test').keyup(function() { 
     var pos = 0; 
     if (this.selectionStart) { 
      pos = this.selectionStart; 
     } else if (document.selection) { 
      this.focus(); 

      var r = document.selection.createRange(); 
      if (r == null) { 
       pos = 0; 
      } else { 

       var re = this.createTextRange(), 
       rc = re.duplicate(); 
       re.moveToBookmark(r.getBookmark()); 
       rc.setEndPoint('EndToStart', re); 

       pos = rc.text.length; 
      } 
     } 
     $('#c').html(this.value.substr(0, pos).split("\n").length); 
    }); 
}); 
​ 

這裏是一個工作示例 http://jsfiddle.net/S2yn3/1/

+0

由換行符引起的線條怎麼樣? –

+0

你是不是指wordwrap? –

+0

是,造成自動換行換行... –

1

這可以分爲三個步驟:

我想你不想考慮包裝文本和滾動的內容。假設您使用的功能從this answer,它會是這樣的:

var el = document.getElementById("inputarea"); // or something 

var pos = getCaret(el), 
    before = el.value.substr(0, pos), 
    lines = before.split(/\r?\n/); 
return lines.length;