Max lines textarea

后端 未结 3 1465
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 14:33

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

 $(document).ready(function(){

        var lines = 10;
        var linesUsed =         


        
相关标签:
3条回答
  • 2020-12-15 15:11

    Well, I couldn't figure out how to calculate the height of only the text inside a textarea, so I used a contenteditable div instead. Hope you like this solution.

    HTML

    <div id="container">
        <div id="rev" contenteditable="true"></div>
    </div>
    

    CSS

    #container {
        height:100px;
        width:300px;
        cursor:text;
        border:1px solid #000
    }
    #rev {
        line-height:20px;
        outline:none
    }
    

    JS

    $(document).ready(function () {
        $('#container').click(function() {
            $('#rev').focus();
        });
    
        var limit = 3;
        var lineHeight = parseInt($('#rev').css('line-height'));
    
        $('#rev').keydown(function (e) {
        var totalHeight = parseInt($('#rev').height());
        var linesUsed = totalHeight / lineHeight;
    
            if (e.keyCode == 13 && linesUsed >= limit) {
                $('#rev').css('color', 'red');
                return false;
            } else {
                $('#rev').css('color', '');
            }
        });
    });
    

    HERE IS A DEMO YOU CAN FIDDLE WITH

    MAJOR EDIT

    Following the OP pointing out I actually forgot to address the most important, I updated my code. I basically removed the check for the enter key and allowed the delete and backspace keys in case the text goes over the limit as follows. You may have to fiddle around with it a little to make it fit to your exact needs.

    $(document).ready(function () {
        $('#container').click(function() {
            $('#rev').focus();
        });
    
        var limit = 3;
        var lineHeight = parseInt($('#rev').css('line-height'));
    
        $('#rev').keydown(function (e) {
        var totalHeight = parseInt($('#rev').height());
        var linesUsed = totalHeight / lineHeight;
    
            if (linesUsed > limit) { // I removed 'e.keyCode == 13 &&' from here
                $('#rev').css('color', 'red');
                if (e.keyCode != 8 && e.keyCode != 46) return false; // I added this check
            } else {
                $('#rev').css('color', '');
            }
        });    
            
        // I added the following lines
        $('#rev').on('paste', function () { 
            if (linesUsed > limit) {
                $('#rev').css('color', 'red');
                if (e.keyCode != 8 && e.keyCode != 46) return false;
            } else {
                $('#rev').css('color', '');
            }
        });
    });
    

    UPDATED DEMO HERE

    0 讨论(0)
  • 2020-12-15 15:23

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

    Here is the UPDATED DEMO

    0 讨论(0)
  • 2020-12-15 15:31

    It's too much work to try to figure how many lines based on the number characters in each line and the textarea width (does the textarea have wrapping off or not? font size, different letter widths, spaces, etc...). The easiest way is to have two textareas (one visible and one not - height set to 0) with the same width and font styles and check the scroll height of the invisible textarea.

    Here is an example http://jsfiddle.net/SKYt4/1/

    HTML

    <textarea id="visible_textarea"></textarea>
    <textarea id="hidden_textarea"></textarea> <!-- hidden by setting the height to 0 -->
    <div id="used_lines"></div>
    

    CSS

    textarea {line-height:16px; /* line height to calculate number of lines */
        width:150px; /* need to match width */}
    #hidden_textarea {height:0px;
        padding:0px;
        border:none;
        margin:0px;
        opacity:0;}
    

    JavaScript

    $('#visible_textarea').keyup(function(){
        $('#hidden_textarea').val(this.value);
        // checking how many lines
        var lns = Math.ceil(document.getElementById('hidden_textarea').scrollHeight / parseInt($('#hidden_textarea').css('line-height')));
    
        if (lns > 10) {
             $('#used_lines').css('color', '#ff0000');
        }
        else {
            $('#used_lines').css('color', '');
        }
    
        $('#used_lines').html(lns+' lines');
    });
    
    
    $('#visible_textarea').change(function(){
        $(this).keyup();
    });
    
    0 讨论(0)
提交回复
热议问题