javascript - 如何计算文本区域中的行数

标签 javascript jquery textarea jquery-events keyup

我想制作一个动态文本区域,它的行数应该随着内容的增加而增加。

我正在使用此代码:

$("#text_textarea").keyup(function(e) {
    //splitting textarea value wrt '\n' to count the number of lines
    if ($(this).val().lastIndexOf('\n')!=-1)
    var x = $(this).val().split('\n');
    $(this).attr( "rows" , x.length+1 );
});

但是当用户继续写入而不给出任何新行\n(按Enter)时,它会失败。

最佳答案

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

这段脚本将更改文本区域的高度以适合内部的文本。

更新

我添加了一个附加功能:为了提高性能(更改 CSS 高度需要大量的计算机能力),我添加了一个冷却效果:仅当用户未启动 keyup 时才会执行高度检查事件持续 500 毫秒(调整此值以满足您的愿望)。

关于javascript - 如何计算文本区域中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7460815/

相关文章:

javascript - Facebook XFBML登录后,通过JavaScript获取用户信息

javascript - 根据下拉选择使输入字段成为必填项

jquery - 如何为我的下拉框激活 selected()

javascript - 在文本区域内添加 Javascript 片段

javascript - JS 意外 token 其他

javascript - getelementbyid 多ID显示

javascript - 如何在多行 <textarea> 中实现自动完成?

internet-explorer - 如何在 selenium webdriver 的富文本编辑器中输入文本?

javascript - .reduce 返回 concat 而不是总和

javascript - 单击弹出窗口中的按钮搜索结果