统计textarea行数,显示,增加,减少

Counting textarea rows, display, increase, decrease

我正在尝试使用纯 javascript 来计算文本区域的行数,但我不确定为什么我的 selector.rows 不是 return 正确的行数:( 这是我的 js:

var selector = document.querySelectorAll("textarea");

for(i = 0; i < selector.length; i++){
   var array = selector[i];
   var count = array.rows;
   console.log(array, count);
   if(count > 1 &&  count.scrollHeight < count.offsetHeight){
       count--
       console.log(array.rows);
   }else{
       count++
       console.log(array.rows);
   }
}

jsFiddle:

上面的代码工作正常,因为它被设计为 return textbox 显示的行数(textarea 的属性 rows)。但是你想要 textarea 中的文本占用的行数,这里有一个解决方案:

  1. 获取textarea的height(我用的是getComputedStyle()因为高度没有定义)
  2. textarea中的内容计算line-height(=高度/行数)。
  3. 获取 textareascrollHeight
  4. 通过将 scrollHeight 除以计算的 line-height 来计算行数。

会是这样的:

var selector = document.querySelectorAll("textarea");

for(i = 0; i < selector.length; i++){
    
    var txtarea = selector[i];
    var count = txtarea.rows;
    
    // get the textarea height
    var cs = window.getComputedStyle(txtarea, null);
    var tHeight = parseInt(cs.getPropertyValue("height"));
  
    // calculate the line-height
    var tLineHeight = tHeight / count;
  
    // calculate the number of rows in the textarea
    var tRows = Math.round(txtarea.scrollHeight / tLineHeight);
  
    document.getElementById("results").innerHTML += "ROWS = " + tRows + "<br>";
    
}//end for
<textarea rows="4" cols="40">
 Lorem ipsum dolor sit amet, eam ex bonorum scripserit. Audire diceret delectus ex usu. Sonet alienum duo id. Elit delenit pro ex, quo case honestatis eloquentiam ea, everti detracto intellegat no nam. Pro quodsi euismod qualisque ei. Est et modus porro, eam solet gubergren ea.

In soleat eleifend per, no per nibh mollis labitur. Sit ei possim molestiae, ius antiopam principes ei. Ea eam soleat fierent. Mel et quod veri convenire, vis no modus oporteat posidonium. Dicunt viderer vocibus his te, qui agam iriure pertinacia te. In sit homero facilisi iudicabit. Timeam eligendi sed an.


</textarea>

<textarea rows="4" cols="40">
 Hello
</textarea>

<div id="results"></div>

您还可以在 JSFiddle 的变体中看到它:http://jsfiddle.net/qxKmW/46/(在这种情况下,请检查控制台日志)


一个问题这个解决方案:它将return这两个中的较高值:

  • 里面内容的行数textarea;或
  • rows 属性中定义的行数(或其默认值)。

这就是为什么在上面的示例中 return 4 而不是第二个 textarea 的 2。一个可能的解决方案是将 rows 属性设置为 1,然后您将始终获得正确的值。