javascript 获取文本区域的行号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12553025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:29:52  来源:igfitidea点击:

Getting Line Number In Text Area

javascriptjqueryhtmltextarea

提问by Freelancer

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 textareaelement.

我想找出用户光标在 HTMLtextarea元素中所在的行号。

Is this possible using javascript and jquery?

这可以使用 javascript 和 jquery 吗?

采纳答案by codingbiz

This works with button click. Stolen from Find out the 'line' (row) number of the cursor in a textarea

这适用于按钮单击。Stolen from在一个textarea中找出光标的'行'(行)号

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

HTML

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" />??????????????????????????????????????????????????????????????????????

回答by Joyce Babu

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.
  1. 找到插入符号位置n(索引)。
  2. 查找从位置 0 到索引的子串
  3. 在步骤 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/

这是一个工作示例 http://jsfiddle.net/S2yn3/1/

回答by Bergi

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;