限制textarea中的行数

我正在寻找一个可以限制行数的javascript(按我的意思是一些文本以用户在键盘上按回车结束),用户可以在textarea中input。 我find了一些解决scheme,但他们根本不工作或行为真的很奇怪。 最好的解决scheme将是一个jQuery的插件,可以做的工作 – 就像CharLimit ,但它应该能够限制文本行数不字符数。

提前致谢。

可能有帮助(可能是最好的使用jQuery,onDomReady和不显眼地添加keydown事件到textarea),但在IE7和FF3testing:

<html> <head><title>Test</title></head> <body> <script type="text/javascript"> var keynum, lines = 1; function limitLines(obj, e) { // IE if(window.event) { keynum = e.keyCode; // Netscape/Firefox/Opera } else if(e.which) { keynum = e.which; } if(keynum == 13) { if(lines == obj.rows) { return false; }else{ lines++; } } } </script> <textarea rows="4" onkeydown="return limitLines(this, event)"></textarea> </body> </html> 

*编辑 – 解释:如果按下ENTER键,它会捕获按键,如果textarea中的行与textarea的行数相同,则不添加新行。 否则,它会增加行数。

如何用jQuery做到这一点:

绑定到textarea的keyDown事件。

 function limitTextareaLine(e) { if(e.keyCode == 13 && $(this).val().split("\n").length >= $(this).attr('rows')) { return false; } } 

此解决scheme工作:

 <script type="text/javascript"> function limitTextarea(textarea, maxLines, maxChar) { var lines = textarea.value.replace(/\r/g, '').split('\n'), lines_removed, char_removed, i; if (maxLines && lines.length > maxLines) { lines = lines.slice(0, maxLines); lines_removed = 1 } if (maxChar) { i = lines.length; while (i-- > 0) if (lines[i].length > maxChar) { lines[i] = lines[i].slice(0, maxChar); char_removed = 1 } if (char_removed || lines_removed) { textarea.value = lines.join('\n') } } } </script> 

和文本区域将是

 <asp:TextBox ID="myWishTB" runat="server" Height="185px" TextMode="MultiLine" Style="overflow: auto;" Width="95%" onkeyup="limitTextarea(this,10,80)"> </asp:TextBox> 

在常规的HTML中:

 <textarea id="textareaID" onkeyup="limitTextarea(this,5,100)" cols="20" rows="5"> </textarea> 

给定文本块的可见/显示行数会因不同的浏览器,使用的字体等而有所不同。您必须至less设置特定的字体和字体大小,以便能够半可靠地计数显示线。

更新:我看到了编辑。 那么像kevchadders代码应该为你做的罚款。 您将需要计算字符和“\ r \ n”的js,并根据用户定义的限制进行检查。 另外,如果你不使用他的脚本,请确保你使用了一个包含时间间隔检查和/或textarea的onKeyDown / onKeyUp事件的脚本。 这可能是为什么你testing过的一些脚本似乎“performance得很奇怪”。

(用jQuery完成)。 这不是完美的,但关心包装。 不仅仅是行结束(\ n)。
jQuery的滚动事件在Mozilla和Firefox中有问题,如果textarea的CSS溢出属性不是自动的,否则删除相应的行并设置隐藏的溢出。 可以帮助resize:没有和固定的高度。

 $('#textarea').scroll(function () { $(this).css("overflow", "hidden"); /* for the mozilla browser problem */ $(this).animate({scrollTop: $(this).outerHeight()}); while ($(this).scrollTop() > 0) { /* for the copy and paste case */ lines=$(this).val().slice(0,-1); $(this).val(lines); } $(this).css("overflow", "auto"); /* For the mozilla browser problem */ }); 

这与使用jQuery的Ivan的答案基本相同。 我testing了一个我自己的项目。 似乎工作正常。

 <script type="text/javascript" charset="utf-8"> $(function() { function getLines(id) { return $('#' + id).val().split("\n").length } $('#testing').keyup(function() { var allowedNumberOfLines = 4; if(getLines('testing') > allowedNumberOfLines) { modifiedText = $(this).val().split("\n").slice(0, allowedNumberOfLines); $(this).val(modifiedText.join("\n")); } }); }); </script> 

jQuery的例子。 这适用于打字和粘贴。

  //Limit to # of rows in textarea or arbitrary # of rows $('#yourtextarea').bind('change keyup', function(event) { //Option 1: Limit to # of rows in textarea rows = $(this).attr('rows'); //Optiion 2: Limit to arbitrary # of rows rows = 6; var value = ''; var splitval = $(this).val().split("\n"); for(var a=0;a<rows && typeof splitval[a] != 'undefined';a++) { if(a>0) value += "\n"; value += splitval[a]; } $(this).val(value); }); 

我扩展了一下,以检测甚至没有手动换行的溢出。 这是固定大小的textarea与“溢出:隐藏”。

目前我的解决scheme使字体更小,如果它不适合textarea。 如果可能的话,再让它变大。

 var keynum, allowedLines = 5, defaultFontSize = 13/*px*/; $(document).ready(function() { $("textarea").keydown(function(e, obj) { if(window.event) keynum = e.keyCode; else if (e.which) keynum = e.which; if (keynum == 13 && allowedLines <= $(this).val().split("\n").length) return false; }); $("textarea").keyup(function(e, obj) { // Avoid copy-paste if (allowedLines < $(this).val().split("\n").length) { lines = $(this).val().split("\n").slice(0, allowedLines); $(this).val( lines.join('\n') ); } // Check overflow if ((this.clientHeight < this.scrollHeight)) { while ((this.clientHeight < this.scrollHeight)) { currFontSize = $(this).css('font-size'); finalNum = parseFloat(currFontSize, 11); stringEnding = currFontSize.slice(-2); $(this).css('font-size', (finalNum-1) + stringEnding); } } else if ($(this).css('fontSize') != defaultFontSize+'px') { while ($(this).css('font-size') != defaultFontSize+'px') { // First lets increase the font size currFontSize = $(this).css('font-size'); finalNum = parseFloat(currFontSize, 11); stringEnding = currFontSize.slice(-2); $(this).css('font-size', (finalNum+1) + stringEnding); // lets loop until its enough or it gets overflow again if(this.clientHeight < this.scrollHeight) { // there was an overflow and we have to recover the value $(this).css('font-size', currFontSize); break; } } } }); });