How to count numbers of line in a textarea

梦想与她 提交于 2019-12-06 11:31:56
var keyUpTimeout = false; // Required variables for performance
var keyupTimer = 0;

$("#text_textarea").keyup(function(e) {
    var cooldownTimeout = 500;
    //Set the cooldown time-out. The height check will be executed when the user
    // hasn't initiated another keyup event within this time

    var ths = this;
    function heightCheck(){
        keyupTimer = false;
        // Reset height, so that the textarea can shrink when necessary
        ths.style.height = "";

        // Set the height of the textarea
        var newheight = this.scrollHeight + 2;
        ths.style.height = newheight + "px";
    }
    if(keyupTimeout){ //Has a cooldown been requested?
        clearTimeout(keyupTimer); //This+next line: Refresh cooldown timeout.
        keyUpTimer = setTimeout(heightCheck, cooldownTimeout);
        return; //Return, to avoid unnecessary calculations
    }

    // Set a cooldown
    keyupTimer = setTimeout(heightCheck, cooldownTimeout);
    keyupTimeout = true; //Request a cooldown
});

This piece of script will change the height of the textarea to fit the text inside.

Update

I have added an additional feature: To improve performance (changing the CSS height requires a significant amount of computer power), I have added a cooldown effect: The height check will only be executed when the user hasn't initiated a keyup event for 500 milliseconds (adjust this value to meet your wishes).

You should use the attribute wrap='hard' on your textarea.

I write this code. what about it..

$("#text_textarea").keyup(function(e) {
    var textarea_height = Number($(this).css('height').replace("px", ""))+4;
    var scroll_height = this.scrollHeight;

    if(textarea_height < scroll_height ){   
        $(this).css('height' ,"");
        var x = Number(scroll_height) + 3;
            if(x != $(this).height()) 
        $(this).css("height", x+"px");
     }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!