查找html textarea中的行数

IT技术 javascript html textarea height line
2021-03-04 02:00:15

我正在编写一个移动 Web 应用程序,其中滚动条不显示在设备的浏览器上。因此,我试图动态修改 textarea 的高度以使其更大,但是我不知道有什么方法可以实际获取 html textarea 的行数。任何帮助将不胜感激!

编辑

所以我现在意识到它本身不是换行符,而是实际的换行符。因此,当一行完成时,它将文本换行到下一行。它看起来好像是一个新行。有什么方法可以计算这些数量吗?谢谢!

6个回答

textarea 中的行数将是

textarea.value.match(/\n/g).length + 1
我正在执行 $(nameofthetextareaid).val().match(/\n/g) 并从调试器接收到 null。我也在引号中尝试了 /\n/g 。
2021-04-22 02:00:15
试试我给你的纯 JavaScript 解决方案,而不是使用 jQuery?
2021-04-22 02:00:15
我现在意识到它是换行而不是换行。您提供的解决方案确实适用于换行符。
2021-05-05 02:00:15

我创建了一个插件来处理<textarea>.
我希望有人可以使用它。

BitBucket 上的代码

示例用法

var result = $.countLines("#textarea");

result.actual   // The number of lines in the textarea.
result.wraps    // The number of lines in the textarea that wrap at least once.
result.wrapped  // The total number of times all lines wrap.
result.blank    // The number of blank lines.
result.visual   // The approximate number of lines that the user actually sees in the textarea  

工作示范

/*! Textarea Line Count - v1.4.1 - 2012-12-06
 * https://bitbucket.org/MostThingsWeb/textarea-line-count
 * Copyright (c) 2012 MostThingsWeb (Chris Laplante); Licensed MIT */

(function($) {
  $.countLines = function(ta, options) {
    var defaults = {
      recalculateCharWidth: true,
      charsMode: "random",
      fontAttrs: ["font-family", "font-size", "text-decoration", "font-style", "font-weight"]
    };

    options = $.extend({}, defaults, options);

    var masterCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    var counter;

    if (!ta.jquery) {
      ta = $(ta);
    }

    var value = ta.val();
    switch (options.charsMode) {
      case "random":
        // Build a random collection of characters
        options.chars = "";
        masterCharacters += ".,?!-+;:'\"";
        for (counter = 1; counter <= 12; counter++) {
          options.chars += masterCharacters[(Math.floor(Math.random() * masterCharacters.length))];
        }
        break;
      case "alpha":
        options.chars = masterCharacters;
        break;
      case "alpha_extended":
        options.chars = masterCharacters + ".,?!-+;:'\"";
        break;
      case "from_ta":
        // Build a random collection of characters from the textarea
        if (value.length < 15) {
          options.chars = masterCharacters;
        } else {
          for (counter = 1; counter <= 15; counter++) {
            options.chars += value[(Math.floor(Math.random() * value.length))];
          }
        }
        break;
      case "custom":
        // Already defined in options.chars
        break;
    }

    // Decode chars
    if (!$.isArray(options.chars)) {
      options.chars = options.chars.split("");
    }

    // Generate a span after the textarea with a random ID
    var id = "";
    for (counter = 1; counter <= 10; counter++) {
      id += (Math.floor(Math.random() * 10) + 1);
    }

    ta.after("<span id='s" + id + "'></span>");
    var span = $("#s" + id);

    // Hide the span
    span.hide();

    // Apply the font properties of the textarea to the span class
    $.each(options.fontAttrs, function(i, v) {
      span.css(v, ta.css(v));
    });

    // Get the number of lines
    var lines = value.split("\n");
    var linesLen = lines.length;

    var averageWidth;

    // Check if the textarea has a cached version of the average character width
    if (options.recalculateCharWidth || ta.data("average_char") == null) {
      // Get a pretty good estimation of the width of a character in the textarea. To get a better average, add more characters and symbols to this list
      var chars = options.chars;

      var charLen = chars.length;
      var totalWidth = 0;

      $.each(chars, function(i, v) {
        span.text(v);
        totalWidth += span.width();
      });

      // Store average width on textarea
      ta.data("average_char", Math.ceil(totalWidth / charLen));
    }

    averageWidth = ta.data("average_char");

    // We are done with the span, so kill it
    span.remove();

    // Determine missing width (from padding, margins, borders, etc); this is what we will add to each line width
    var missingWidth = (ta.outerWidth() - ta.width()) * 2;

    // Calculate the number of lines that occupy more than one line
    var lineWidth;

    var wrappingLines = 0;
    var wrappingCount = 0;
    var blankLines = 0;

    $.each(lines, function(i, v) {
      // Calculate width of line
      lineWidth = ((v.length + 1) * averageWidth) + missingWidth;
      // Check if the line is wrapped
      if (lineWidth >= ta.outerWidth()) {
        // Calculate number of times the line wraps
        var wrapCount = Math.floor(lineWidth / ta.outerWidth());
        wrappingCount += wrapCount;
        wrappingLines++;
      }

      if ($.trim(v) === "") {
        blankLines++;
      }
    });

    var ret = {};
    ret["actual"] = linesLen;
    ret["wrapped"] = wrappingLines;
    ret["wraps"] = wrappingCount;
    ret["visual"] = linesLen + wrappingCount;
    ret["blank"] = blankLines;

    return ret;
  };
}(jQuery));



result = jQuery.countLines("#textarea");

jQuery('#display').html(
  '<span>Actual: ' + result.actual + '</span>' +
  '<span>Blank: ' + result.blank + '</span>' +
  '<span>Visual: ' + result.visual + '</span>' +
  '<span>Wrapped: ' + result.wrapped + '</span>' +
  '<span>Wraps: ' + result.wraps + '</span>'
);
#textarea {
  width: 150px;
  height: 80px;
}
#display span {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea">text
here
  
this is a longer line so that it will wrap in the box longer longer longer</textarea>

<div id="display"></div>

如果您将代码添加到答案中,这样您的解决方案就不会依赖于不可靠的外部链接,那就太好了。
2021-05-01 02:00:15
谢谢@ChrisLaplante。很酷的插件。我冒昧地在你的帖子中添加了一个工作演示。如果您不喜欢它,请随时回滚编辑。
2021-05-16 02:00:15
@showdev:抱歉链接不好。使用这个:bitbucket.org/MostThingsWeb/textarea-line-count
2021-05-18 02:00:15

这是一种计算文本区域中行数(包括换行数)的有效且准确的方法。

/** @type {HTMLTextAreaElement} */
var _buffer;

/**
* Returns the number of lines in a textarea, including wrapped lines.
*
* __NOTE__:
* [textarea] should have an integer line height to avoid rounding errors.
*/
function countLines(textarea) {
    if (_buffer == null) {
        _buffer = document.createElement('textarea');
        _buffer.style.border = 'none';
        _buffer.style.height = '0';
        _buffer.style.overflow = 'hidden';
        _buffer.style.padding = '0';
        _buffer.style.position = 'absolute';
        _buffer.style.left = '0';
        _buffer.style.top = '0';
        _buffer.style.zIndex = '-1';
        document.body.appendChild(_buffer);
    }

    var cs = window.getComputedStyle(textarea);
    var pl = parseInt(cs.paddingLeft);
    var pr = parseInt(cs.paddingRight);
    var lh = parseInt(cs.lineHeight);

    // [cs.lineHeight] may return 'normal', which means line height = font size.
    if (isNaN(lh)) lh = parseInt(cs.fontSize);

    // Copy content width.
    _buffer.style.width = (textarea.clientWidth - pl - pr) + 'px';

    // Copy text properties.
    _buffer.style.font = cs.font;
    _buffer.style.letterSpacing = cs.letterSpacing;
    _buffer.style.whiteSpace = cs.whiteSpace;
    _buffer.style.wordBreak = cs.wordBreak;
    _buffer.style.wordSpacing = cs.wordSpacing;
    _buffer.style.wordWrap = cs.wordWrap;

    // Copy value.
    _buffer.value = textarea.value;

    var result = Math.floor(_buffer.scrollHeight / lh);
    if (result == 0) result = 1;
    return result;
}

演示在这里

这太棒了!除了标准的 ASCII 码,我还用 UTF-8 表情符号和外语字素测试了它,它完美无缺。
2021-04-23 02:00:15
您缺少将 fontSize 和 fontFamily 设置为 _buffer。至少我有问题但是很棒:)
2021-05-04 02:00:15

我还没有尝试使用本博客中讨论的功能,但您可能会发现它很有用。

http://kirblog.idetalk.com/2010/03/calculating-cursor-position-in-textarea.html

基本上,如果您创建一个div然后将文本复制到该 div 中,具有相同的宽度和字体特征,您就可以获得所需的信息,例如行数。这个例子中的行数很简单,因为如果你知道一条线有多少像素高,那么只要找到测试 div 的宽度,你就可以得到关于有多少行的非常准确的想法你的textarea

@MattCoughlin - 你是对的,它不会是准确的,这就是为什么我选择了“非常准确的想法”。:)
2021-05-01 02:00:15
这将是接近但不准确的。在某些浏览器中,textarea 与 div 仍然存在细微差别,例如 textarea 内的隐式填充,除非移除边框(Firefox),否则无法删除,或者除非设置了 overflow:hidden,否则会出现禁用的垂直滚动条(IE)。临时更改这些 textarea 样式以与 div 保持一致将更改 textarea 的有效宽度并使结果倾斜,就像不更改它们一样。如果值得麻烦的话,我想如果使用浏览器嗅探来自定义 div 可能会更准确。
2021-05-17 02:00:15

获取scrollHeight,减去顶部+底部填充,除以 lineHeight。

当 textarea 中的行数少于 textarea 的高度时,此解决方案失败。
2021-04-24 02:00:15