js根据输入的文本自动改变textarea框的高度

js根据输入的文本自动改变textarea框的高度

/*** 根据输入的文本自动改变textarea框的高度   
  	@param {string} el 元素对象 如: document.querySelector(".list")
  	@param {number} maxHeight 最大高度
  	@param {number} minHeight 最小高度
  	@example: autoTextarea(document.querySelector("#textarea"), 300, 100);
 */
function autoTextarea(el, maxHeight, minHeight){
	el.onchange = el.oninput = el.onpaste = el.oncut = el.onkeydown = el.onkeyup = el.onfocus = el.onblur = function(){
		var height,style=this.style;
        this.style.height = minHeight + 'px';
        if (this.scrollHeight > minHeight)
        {
	        if (maxHeight && this.scrollHeight > maxHeight)
	        {
	            height = maxHeight;
	            style.overflowY = 'scroll';
	        }
	        else
	        {
	            height = this.scrollHeight;
	            style.overflowY = 'hidden';
	        }
	        style.height = height + 'px';
        }
	}
}
posted @ 2020-12-31 09:51  风如白话  阅读(462)  评论(0编辑  收藏  举报