Max lines textarea

后端 未结 3 1472
爱一瞬间的悲伤
爱一瞬间的悲伤 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

    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

提交回复
热议问题