计算没有jQuery的HTML textarea中显示的行数(不是换行符)?

Naz*_*azi 9 html javascript textarea line-count

可能重复:
如何获取<textarea>中的行数?

我有一个textarea和我7 lines在其中写的只是2 new line character如下,想象下面的代码框是一个textarea,只有两次输入键被按下.

 A text box, text field or text entry box is a kind of widget used when building
 a graphical user interface (GUI). A text box purpose is to allow the user to
 input text information to be used by the program.
 User-interface guidelines recommend a single-line text box when only one line of
 input is required, and a multi-line text box only if more than one line of input
 may be required.
 Non-editable text boxes can serve the purpose of simply displaying text.
Run Code Online (Sandbox Code Playgroud)

如果现在textarea line count是写了更多的行n.我怎样才能计算出的价值n??

在回答问题之前请说清楚.我不想算new line characters我的文本中有多少像这样.如何获得textarea中的行数?

我想计算行数,就像Microsoft Word从段落中计算它一样.

没有jQuery请...

Ace*_*Ace 3

你可以试试这个。到目前为止我还没有测试过,但我记得这应该可以正常工作。

var lineHeight = document.getElementById("yourTextarea").style.lineHeight;
var scrollHeight = document.getElementById("yourTextarea").scrollHeight;
document.getElementById("yourTextarea").style.height = scrollHeight; // this is just for showing purposes
var numLines = Math.floor( scrollHeight / lineHeight );
Run Code Online (Sandbox Code Playgroud)

这应该是我认为最简单的方法。

编辑

所以这就是答案,就这么简单:D

首先让 Shure 为文本区域指定cols

现在看看这个=

<textarea id="mytext" cols="10" rows="12">
</textarea>
<input type="button" value="Count Rows" onclick="countRows();"/>
<script type="text/javascript">
function countRows() {
    var stringLength = document.getElementById("mytext").value.length;
    var count = Math.ceil( stringLength / document.getElementById("mytext").cols ); 
    // just devide the absolute string length by the amount of horizontal place and ceil it
    alert( count );
}
</script>
Run Code Online (Sandbox Code Playgroud)

现在这应该可以正常工作。

更新

您还可以确保在获取长度之前删除所有“换行”元素或仅删除最后一个字符(如果它是字符串中的“换行”)。这样就不会计算不需要的额外行。

另外请务必不要设置文本框的“宽度”!这将导致行中的文本比“cols”的值更远。这样,如果具有 max-row-width 的 cols 值,“count”值将为您提供行数。所以使用 cols 属性设置文本框宽度的唯一方法。

更新2

我认为如果你想要一种无错误的方式,就没有办法使用 PHP 或 jQuery。

另外,第二种解决方案只是一种快速而肮脏的方法。您必须编写一个逻辑来检查每个单词是否长于可离开的宽度,并检查每行是否有由于空间不足而被放入下一行的单词。

这将需要一些逻辑技能,由于不活动,我现在不会编写代码。

如果您希望我发布完整的 Javascript、PHP 或 jQuery 解决方案,请告诉我。(我看不出有什么理由不使用 jQuery )