我正在尝试使用纯 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);
}
}
最佳答案
上面的代码工作正常,因为它旨在返回 textbox
显示的行数(textarea
的属性 rows
>).但是你想要 textarea
中的文本占用的行数,这里是一个解决方案:
- 获取文本区域的
高度
(我使用了getComputedStyle()
,因为高度没有定义) - 计算
textarea
中内容的line-height
(= 高度/行数)。 - 获取
textarea
的scrollHeight
。 - 通过将
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/