最大行textarea [英] Max lines textarea

查看:126
本文介绍了最大行textarea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一些限制textarea中使用的行的脚本,如下所示:

I have found some scripts that limit the lines used in a textarea like this:

 $(document).ready(function(){

        var lines = 10;
        var linesUsed = $('#linesUsed');
        var newLines=0;

        $('#rev').keydown(function(e) {

            newLines = $(this).val().split("\n").length;
            linesUsed.text(newLines);

            if(e.keyCode == 13 && newLines >= lines) {
                linesUsed.css('color', 'red');
                return false;
            }
            else {
                linesUsed.css('color', '');
            } 
        }); 

当你按Enter键并将其限制为10时,它可以正常工作。但是当你输入这么长的句子时会出现问题自动转到没有\\\
的新行,当你复制粘贴文本时,它无法限制使用的行。

It works fine when you hit enter and limits it to 10 .But the problem occurs when you type sentences that are so long they automatically go to a new line without the \n and when you copy paste a text, then it fails to limit the lines used.

有没有人知道如何解决这个问题。

does anyone know how to fix this.

重要:解决方案需要适用于textarea

Important: solution needs to work for a textarea

推荐答案

您可以尝试使用此逻辑:

You could try doing it using this logic:

var limit = 3; // <---max no of lines you want in textarea
var textarea = document.getElementById("splitLines");
var spaces = textarea.getAttribute("cols");

textarea.onkeyup = function() {
   var lines = textarea.value.split("\n");

   for (var i = 0; i < lines.length; i++) 
   {
         if (lines[i].length <= spaces) continue;
         var j = 0;

        var space = spaces;

        while (j++ <= spaces) 
        {
           if (lines[i].charAt(j) === " ") space = j;  
        }
    lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
    lines[i] = lines[i].substring(0, space);
  }
    if(lines.length>limit)
    {
        textarea.style.color = 'red';
        setTimeout(function(){
            textarea.style.color = '';
        },500);
    }    
   textarea.value = lines.slice(0, limit).join("\n");
};

这是 更新的演示

这篇关于最大行textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆