当前位置: 首页 > Web前端 > HTML5

制作一个可适应高度1的textarea

时间:2023-04-05 20:33:37 HTML5

方法  。HTML结构:

  2。CSS代码:*{填充:0;保证金:0;}#container{宽度:300px;填充:10px;边框:1px实心#eee;框大小:边框框;}textarea{显示:块;宽度:100%;字体大小:20px;颜色:#000;行高:24px;大纲:无;边框:无;调整大小:无;}  3.JS代码:vartextarea=document.querySelector('textarea')varinpnt=(function(){varbaseHeight=nullreturnfunction(){!baseHeight&&(baseHeight=this.scrollHeight)this.rows=1varrows=Math.ceil(this.scrollHeight/baseHeight)>=3?3:Math.ceil(this.scrollHeight/baseHeight)this.rows=rows}})()textarea.oninput=debounce(inpnt,100)functiondebounce(func,delay){vartimer=nullreturnfunction(){var_this=thisvarargs=argumentstimer&&clearTimeout(timer)timer=setTimeout(function(){func.apply(_this,args)},delay)}}原理!baseHeight&&(baseHeight=this.scrollHeight)this.rows=1varrows=Math.ceil(this.scrollHeight/baseHeight)>=3?3:Math.ceil(this.scrollHeight/baseHeight)this.rows=rows第一行获取基础高度,缓存第二行重点是将textarea的行数设置为1,这样当前textarea的scrollHeight可以得到。第三行获取当前textarea的scrollHeight,可以计算行数。第四行设置textarea的行数,通过设置textarea的rows属性改变textarea的高度。