Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

javascript - Max lines 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("
").length;
            linesUsed.text(newLines);

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

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 and when you copy paste a text, then it fails to limit the lines used.

does anyone know how to fix this.

Important: solution needs to work for a textarea

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could try doing it using this logic:

JS :

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("
");

   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("
");
};

Here is the UPDATED DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...