您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)怎么實(shí)現(xiàn)一個(gè)自適應(yīng)高度的textarea,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
方法
1. HTML結(jié)構(gòu):
<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
第一行 獲取基準(zhǔn)高度 緩存起
第二行 重點(diǎn) 將textarea的rows設(shè)置成1 這樣就能得到當(dāng)前textarea的scrollHeight
第三行 拿到了當(dāng)前textarea的scrollHeight 就可以算出rows
第四行 設(shè)置textarea的rows
通過設(shè)置textarea的rows屬性來改變textarea的高度。
看完上述內(nèi)容,你們對(duì)怎么實(shí)現(xiàn)一個(gè)自適應(yīng)高度的textarea有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。