23

Possible Duplicate:
Find out the 'line' (row) number of the cursor in a textarea

I want to find out the line number that a user's cursor in on in a HTML textarea element.

Is this possible using javascript and jquery?

4

3 回答 3

20

这适用于按钮单击。从查找文本区域中光标的“行”(行)号中窃取

​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" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
于 2012-09-23T14:27:25.780 回答
1

You can use the following approach

  1. Find the caret position (index).
  2. Find the substring from position 0 to index
  3. Search for number of new lines in the substring obtained in step 2.

// Test

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

Here is a working example http://jsfiddle.net/S2yn3/1/

于 2012-09-23T14:16:21.637 回答
1

This can be split up in three steps:

I guess you don't want to consider wrapped text and scrolled content. Assuming you use the function from this answer, it would be like:

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;
于 2012-09-23T14:21:21.670 回答