如何计算textarea中的行数 [英] How to count numbers of line in a textarea
问题描述
我想创建一个动态textarea,它会随着内容的增加而增加行数。
I want to make a dynamic textarea, it should increase in rows as the content increase.
我正在使用此代码:
$("#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键)。
But it fails when user continues to write without giving any new line \n
(pressing 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
});
这段脚本将改变文本区域的高度以适应文本内部。
This piece of script will change the height of the textarea to fit the text inside.
我添加了一项附加功能:提高性能(更改CSS高度需要大量的计算机电源) ,我添加了一个冷却效果:高度检查只会在用户未启动 keyup
事件500毫秒时执行(调整此值以满足您的意愿) 。
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).
这篇关于如何计算textarea中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!