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
});
这段脚本将改变 textarea 的高度以适应里面的文本。
更新
keyup
我添加了一个附加功能:为了提高性能(更改 CSS 高度需要大量的计算机功率),我添加了一个冷却效果:只有在用户500 毫秒内没有发起事件时才会执行高度检查(调整此值以满足您的意愿)。