簡體   English   中英

查找html textarea中的行數

[英]Finding number of lines in an html textarea

我正在編寫一個移動Web應用程序,其中滾動條不會顯示在設備的瀏覽器上。 因此,我正在嘗試動態修改textarea的高度以使其更大,但我不知道有什么方法可以在html textarea上實際獲取行數。 任何幫助將不勝感激!

編輯

所以我現在意識到這不是新行本身,而是實際換行。 因此,當一行完成時,它將文本包裝到下一行。 它看起來好像是一條新線。 有沒有辦法計算這些數量? 謝謝!

textarea中的行數是

textarea.value.match(/\n/g).length + 1

我已經創建了一個插件來處理<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> 

我沒有嘗試使用本博客中討論的功能,但您可能會發現它很有用。

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

基本上,如果您創建一個div然后將文本復制到具有相同寬度和字體特征的div中,則可以獲得所需的信息,例如行數。 這個例子中的行數很容易,因為如果你知道單行的像素數是多少,那么只需找到測試div的寬度,就可以得到一個非常准確的想法。你的textarea

這是一種有效且准確的方法來計算文本區域中的行數,包括包裹的行。

/** @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;
}

在這里演示

獲取scrollHeight ,減去top + bottom padding,除以lineHeight。

我很確定沒有合理的方法來計算瀏覽器中顯示的行數,特別是考慮到某些瀏覽器(Safari)允許用戶調整textareas的大小。

它是hacky,但你最好的選擇可能只是根據總字符數除以每行的平均字符數來估算。 : - /

也許有辦法獲得“原始”數量的“視覺”線。 您應該閱讀textarea的scrollHeight屬性並將其除以線的高度。 我們試試吧。

從這個HTML開始:

<textarea id="ta" cols="50" rows="10"></textarea>

然后:

var line_height = Math.floor($("#ta").height() / parseInt($("#ta").attr("rows")));
var dirty_number_of_lines = Math.ceil($("#ta")[0].scrollHeight / line_height);

我不確定這是否真的有效,只是一個瘋狂的理論。

你可以這樣計算:

var length = $('#textarea').val().split("\n").length;

每行允許的字符數由textarea的“cols”屬性決定。

<textarea rows="10" cols="80"></textarea>

假設每行80個字符,一個好的估計可能是:

var approxNumLines = textareaElement.value.length / textareaElement.cols ;

不考慮分詞和自動換行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM