好像有在工具沒有建立得到這個值。但我們可以計算出來。 假設textarea中的行高是一個已知值(您可以在css中明確定義它)。因此,代碼計算行數將是這樣的:
var area = $('#myarea').get(0);
//save the initial height of textarea
var initialHeight = area.style.height;
//set the height to 0 so scrollHeight will always return dynamic height
area.style.height = '0px';
//here we assume that the line-height equals to 15
var numberOfRows = Math.floor(area.scrollHeight/15);
//restore textarea height
area.style.height = initialHeight;
console.log(numberOfRows);
工作實例http://jsfiddle.net/J5UpF/
UPDATE
只是想出了在Chrome的bug我的代碼。我沒有考慮textarea右側出現的滾動條。這導致有時計算錯誤的行數。然而,它在Firefox中像一個魅力。爲了解決這個問題,我們來計算滾動條寬度的差異,調整文本區域的相應寬度:
var area = $('#myarea').get(0);
var $area = $('#myarea');
//save the initial height of textarea
var initialHeight = area.style.height;
var scrollbarWidthInitial = area.offsetWidth - area.clientWidth;
//set the height to 0 so scrollHeight will always return dynamic height
area.style.height = '0px';
var scrollbarWidth = area.offsetWidth - area.clientWidth;
var scrollbarWidthDiff = scrollbarWidth - scrollbarWidthInitial;
$area.width($area.width() + scrollbarWidthDiff);
//here we assume that the line-height equals to 15
var numberOfRows = Math.floor(area.scrollHeight/15);
//restore textarea height
area.style.height = initialHeight;
$area.width($area.width() - scrollbarWidthDiff);
console.log(numberOfRows);
更新例如http://jsfiddle.net/J5UpF/3/
更新2
Chrome新真棒錯誤是發現! Chrome使用placeholder
屬性計算佔位符文本的行數。解決方法很簡單:只需在將某些數據輸入到textarea中時備份佔位符屬性,並在清除數據時恢復它。
更新例如http://jsfiddle.net/J5UpF/4/
_「爲什麼可以在服務器解釋(發現)的新生產線,而我不能?」 _ - http://www.w3.org/TR/html5/forms.html# attr-textarea-wrap – CBroe
謝謝你的鏈接。根據我的理解(很少有)我不能找到「LF」(U + 000A)字符?如果是這樣的話,那麼我期待的是什麼「性格」? :) – Whyser
源自wrap = hard的換行符不包含在您可以使用JS讀取的'value'屬性中 - 它們是「提交值」的一部分,但是AFAIK在「計算」它時由瀏覽器決定 - 可能就在表單被提交的那一刻。 – CBroe