【问题标题】:Getting Line Number In Text Area [duplicate]在文本区域中获取行号[重复]
【发布时间】:2023-04-11 00:42:01
【问题描述】:

可能重复:
Find out the 'line' (row) number of the cursor in a textarea

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

这可以使用 javascript 和 jquery 吗?

【问题讨论】:

  • 在文本区域中定义行。它是包含换行的文本还是您只想考虑换行符?
  • 我想在一行中设置 15 个字符的限制,用户应该不能在 5 行中输入超过 75 个字符
  • 很好的问题真的 :) 喜欢和书签 ;)

标签: javascript jquery html textarea


【解决方案1】:

这适用于按钮单击。盗自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" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

【讨论】:

  • 这不考虑换行引起的换行。
  • @RobW:我认为 OP 不需要这样
  • 它对我有用...很有帮助
  • @codingbiz:太完美了……我只是复制并粘贴了它……它已经奏效了……我过去 1 周都在这个问题中……但我已经发布了现在..谢谢你..
  • @freelance 祝你好运
【解决方案2】:

这可以分为三个步骤:

我猜你不想考虑包装文本和滚动内容。假设您使用来自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;

【讨论】:

    【解决方案3】:

    您可以使用以下方法

    1. Find the caret position(索引)。
    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/

    【讨论】:

    • 换行导致的行怎么办?
    • 你是说自动换行吗?
    • 是的,换行引起的换行...
    • 很难检测由自动换行引起的换行,除非你使用的是固定宽度的字体。
    猜你喜欢
    • 2011-07-02
    • 2013-02-03
    • 1970-01-01
    • 2020-09-10
    • 2012-09-02
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多