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

标签 javascript html rows

我正在尝试使用纯 javascript 计算文本区域的行数,但我不确定为什么我的 selector.rows 没有返回正确的行数:( 这是我的 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:

最佳答案

上面的代码工作正常,因为它旨在返回 textbox 显示的行数(textarea 的属性 rows >).但是你想要 textarea 中的文本占用的行数,这里是一个解决方案:

  1. 获取文本区域的高度(我使用了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/ (在这种情况下,检查控制台日志)


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

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

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

关于javascript - 统计textarea行数,显示,增加,减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30215959/

相关文章:

javascript - 是否可以使我的 ECharts 折线图更加紧凑?

html - 如何将外部字体加载到 HTML 文档中?

python - 从其他数据框中选择具有特定条件的行

SQL - STUFF 函数中的 CASE WHEN 作为条件分隔符

javascript - parseFloat 不能使用小数点后的零

javascript - 计算填充的输入数

html - iframe 填充不同平台上剩余的可见空间

javascript - 如何使用 Twig 检测屏幕尺寸或移动/桌面

MySQL查询根据另一个字段枚举行

javascript - KendoUI 工具栏 splitButton 自动突出显示下拉列表中的第一个选项。如何使所有选项看起来都一样