找出textarea中光标的"line"(行)编号

eth*_*k3r 22 javascript textarea

我想找出并跟踪textarea中光标的"行号"(行).("更大的图片"是每次创建/修改/选择新行时解析行上的文本,如果当然没有粘贴文本.这样可以节省解析整个文本的时间间隔.)

StackOverflow上有几个帖子,但没有一个专门回答我的问题,大多数问题是光标位置(以像素为单位)或显示除textarea之外的行号.

我的尝试在下面,它从第1行开始并且不离开textarea时工作正常.单击textarea并在另一行上返回时,它会失败.将文本粘贴到其中时也会失败,因为起始行不是1.

我的JavaScript知识非常有限.

<html>

<head>
<title>DEVBug</title>

<script type="text/javascript">

    var total_lines = 1; // total lines
    var current_line = 1; // current line
    var old_line_count;

    // main editor function
    function code(e) {

        // declare some needed vars
        var keypress_code = e.keyCode; // key press
        var editor = document.getElementById('editor'); // the editor textarea
        var source_code = editor.value; // contents of the editor

        // work out how many lines we have used in total    
            var lines = source_code.split("\n");
            var total_lines = lines.length;

    // do stuff on key presses
    if (keypress_code == '13') { // Enter
        current_line += 1;
    } else if (keypress_code == '8') { // Backspace
        if (old_line_count > total_lines) { current_line -= 1; }
    } else if (keypress_code == '38') { // Up
        if (total_lines > 1 && current_line > 1) { current_line -= 1; }
    } else if (keypress_code == '40') { // Down
        if (total_lines > 1 && current_line < total_lines) { current_line += 1; }
    } else {
        //document.getElementById('keycodes').innerHTML += keypress_code;
    }

    // for some reason chrome doesn't enter a newline char on enter
    // you have to press enter and then an additional key for \n to appear
    // making the total_lines counter lag.
    if (total_lines < current_line) { total_lines += 1 };

    // putput the data
    document.getElementById('total_lines').innerHTML = "Total lines: " + total_lines;
    document.getElementById('current_line').innerHTML = "Current line: " + current_line;

    // save the old line count for comparison on next run
    old_line_count = total_lines;

}

</script>

</head>

<body>

<textarea id="editor" rows="30" cols="100" value="" onkeydown="code(event)"></textarea>
<div id="total_lines"></div>
<div id="current_line"></div>

</body>

</html>
Run Code Online (Sandbox Code Playgroud)

cal*_*leb 35

你可能想用selectionStart它来做这件事.

<textarea onkeyup="getLineNumber(this, document.getElementById('lineNo'));" onmouseup="this.onkeyup();"></textarea>
<div id="lineNo"></div>

<script>

    function getLineNumber(textarea, indicator) {

        indicator.innerHTML = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
    }

</script>
Run Code Online (Sandbox Code Playgroud)

当您使用鼠标更改光标位置时也可以.

  • 如果textarea中存在软线交换,则此解决方案将无效.示例:创建一个包含10列的textarea,在其中添加几个单词,使文本溢出到2-3行 - 但不要在其中添加换行符.上面的代码将始终返回1,因为textarea中没有"\n"字符 - 但用户实际上看到的行超过1行.这是TEXTAREAs的真正困难......我真的很惊讶现代浏览器中没有任何标准的API ... (26认同)
  • 这并不适用于所有情况。如果你输入没有换行符的文本,上面的函数总是返回 1。但它可能是 2 或更多。 (2认同)

小智 22

由于自动换行,这很难.计算存在的换行数是一件非常容易的事情,但是当新行是由于自动换行时会发生什么?要解决此问题,创建镜像很有用(credit:github.com/jevin).这是个主意:

  1. 创建textarea的镜像
  2. 将文本从textarea的开头发送到光标到镜像
  3. 使用镜像的高度来提取当前行

在JSFiddle上

jQuery.fn.trackRows = function() {
    return this.each(function() {

    var ininitalHeight, currentRow, firstIteration = true;

    var createMirror = function(textarea) {
        jQuery(textarea).after('<div class="autogrow-textarea-mirror"></div>');
        return jQuery(textarea).next('.autogrow-textarea-mirror')[0];
    }

    var sendContentToMirror = function (textarea) {
        mirror.innerHTML = String(textarea.value.substring(0,textarea.selectionStart-1)).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br />') + '.<br/>.';
        calculateRowNumber();
    }

    var growTextarea = function () {
        sendContentToMirror(this);
    }

    var calculateRowNumber = function () {
        if(firstIteration){
            ininitalHeight = $(mirror).height();
            currentHeight = ininitalHeight;
            firstIteration = false;
        } else {
            currentHeight = $(mirror).height();
        }
        // Assume that textarea.rows = 2 initially
        currentRow = currentHeight/(ininitalHeight/2) - 1;
        //remove tracker in production
        $('.tracker').html('Current row: ' + currentRow);
    }

    // Create a mirror
    var mirror = createMirror(this);

    // Style the mirror
    mirror.style.display = 'none';
    mirror.style.wordWrap = 'break-word';
    mirror.style.whiteSpace = 'normal';
    mirror.style.padding = jQuery(this).css('padding');
    mirror.style.width = jQuery(this).css('width');
    mirror.style.fontFamily = jQuery(this).css('font-family');
    mirror.style.fontSize = jQuery(this).css('font-size');
    mirror.style.lineHeight = jQuery(this).css('line-height');

    // Style the textarea
    this.style.overflow = "hidden";
    this.style.minHeight = this.rows+"em";

    var ininitalHeight = $(mirror).height();

    // Bind the textarea's event
    this.onkeyup = growTextarea;

    // Fire the event for text already present
    // sendContentToMirror(this);

    });
};

$(function(){
    $('textarea').trackRows();
});
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案.我没有测试过代码,但它至少尝试了一种处理软换行的工作解决方案. (5认同)