方式
1. HTML构造:
<div id="container"> <textarea rows="1"></textarea> </div>
2. CSS编码:
* { padding: 0; margin: 0; } #container { width: 300px; padding: 10px; border: 1px solid #eee; box-sizing: border-box; } textarea { display: block; width: 100%; font-size: 20px; color: #000; line-height: 24px; outline: none; border: none; resize: none; }
3. JS编码:
var textarea = document.querySelector('textarea') var inpnt = (function () { var baseHeight = null return function () { !baseHeight && (baseHeight = this.scrollHeight) this.rows = 1 var rows = Math.ceil(this.scrollHeight / baseHeight) >= 3 ? 3 : Math.ceil(this .scrollHeight / baseHeight) this.rows = rows } })() textarea.oninput = debounce(inpnt, 100) function debounce(func, delay) { var timer = null return function () { var _this = this var args = arguments timer && clearTimeout(timer) timer = setTimeout(function () { func.apply(_this, args) }, delay) } }
基本原理
!baseHeight && (baseHeight = this.scrollHeight) this.rows = 1 var rows = Math.ceil(this.scrollHeight / baseHeight) >= 3 ? 3 : Math.ceil(this .scrollHeight / baseHeight) this.rows = rows
第1行 获得标准高宽比 缓存文件起
第2行 关键 将textarea的rows设定成1 这样就可以获得当今textarea的scrollHeight
第3行 拿到了当今textarea的scrollHeight 便可以算出rows
第4行 设定textarea的rows
根据设定textarea的rows特性来更改textarea的高宽比。
以上便是本文的所有內容,期待对大伙儿的学习培训有一定的协助,也期待大伙儿多多适用脚本制作之家。