我试图使用纯javascript计算textarea行数,但我不确定为什么我的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
显示的行数(属性rows
)。但是您需要textarea
中的文本所占用的行数,这里有一个解决方案:
获取文本区域的textarea
(由于未定义高度,我使用了height
)
计算getComputedStyle()
中内容的line-height
(=高度/行)。
获取textarea
的scrollHeight
。
通过将textarea
除以计算的scrollHeight
来计算行数。
可能是这样的:
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/(在本例中,请查看控制台日志)
此解决方案的一个问题是:它将返回这两个值中的较高值:
line-height
中内容的行数;或textarea
属性中定义的行数(或其默认值)。这就是为什么在上面的示例中,第二个
rows
将返回4而不是2。可能的解决方案是将textarea
属性设置为1,然后您将始终获得正确的值。