限制Textarea中每行的字符数

限制Textarea中每行的字符数

问题描述:

我整个周末都在寻找解决这个问题的方法,并且尚未找到一个正常工作的解决方案。我想要改进的是限制textarea中每行的charatcers数量 - 不限制它们相同,但我选择的每行字符数不同。

I have been searching all weekend for the solution to this quandry and have yet to find a solution that works correctly. What I am trying to acchieve is to limit the number of charatcers per line in a textarea - not limiting them identically, but a different number of characters per line of my choosing.

例如:


  1. 我想在textarea中只有4行

  2. 第1,2和3行将限制为24个字符

  3. 第4行将包含无限数量的字符

这是可能的textarea,还是有另一种方式来做一个Div或其他东西。我确实意识到这很可能已经被覆盖过了,但是找到一个覆盖这个标准的实际工作脚本已经证明是非常困难的,而且我没有足够的技能来取得这些结果。

Is this possible with a textarea, or is there another way of doing i with a Div or something. I do realise that this has in all likelihood been covered before, but to find an actual working script that covers this criterium has proved extremely difficult and I don't have the kind of skill it takes to acchieve these results.

谢谢

以下是您尝试的问题的示例快照解决:

Below is a sample snapshot of the problem that you're trying to solve:


  • textarea中的4行(限制在textarea本身上,行=4)

  • 第1,2和3行限制为24个字符

  • 第4行将包含无限数量的字符

textarea的快照:

123456789012345678901234
123456789012345678902333
232323232323232323323232
23232323232323232323236464536543654643

JavaScript:

$('#your-input').keypress(function() {
     var text = $(this).val();
     var arr = text.split("\n");

     if(arr.length > 5) {
         alert("You've exceeded the 4 line limit!");
         event.preventDefault(); // prevent characters from appearing
     } else {
         for(var i = 0; i < arr.length; i++) {
             if(arr[i].length > 24 && i < 3) {
                 alert("Length exceeded in line 1, 2, or 3!");
                 event.preventDefault(); // prevent characters from appearing
             }
         }
     }

     console.log(arr.length + " : " + JSON.stringify(arr));
});

这可以使用按键事件来完成。触发按键事件时,获取文本框的当前值,并使用 \ n 换行符作为分隔符将值拆分为数组。

This can be accomplished using a keypress event. When the keypress event fires, get the current value of the textbox and split the value into an array using the \n line break character as a delimiter.


  • 数组的长度告诉你你有多少行。如果您已超出这些线路,我们会发出警报。

  • 数组中每个字符串的长度表示每行的长度。我们使用for循环来检查前3行。如果我们超过24的长度,我们会发出警报。

  • 我们忽略循环的最后一次迭代,因为我们不关心最后一行的长度。

这不是一个完整的解决方案,但这肯定会让你开始并为你提供一些你可以修改的东西,以满足你的需求。祝你好运!

This is not designed to be a complete solution, but this will definitely get you started and provide you with something that you can modify to suit your needs. Good luck!