我想制作一个动态文本区域,它的行数应该随着内容的增加而增加。
我正在使用此代码:
$("#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/