今天就跟大家聊聊有關怎么實現一個自適應高度的textarea,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。

創新互聯是一家專業提供伊通企業網站建設,專注與網站設計、成都網站建設、HTML5建站、小程序制作等業務。10年已為伊通眾多企業、政府機構等服務。創新互聯專業網站建設公司優惠進行中。
方法
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
第一行 獲取基準高度 緩存起
第二行 重點 將textarea的rows設置成1 這樣就能得到當前textarea的scrollHeight
第三行 拿到了當前textarea的scrollHeight 就可以算出rows
第四行 設置textarea的rows
通過設置textarea的rows屬性來改變textarea的高度。
看完上述內容,你們對怎么實現一個自適應高度的textarea有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注創新互聯行業資訊頻道,感謝大家的支持。
                標題名稱:怎么實現一個自適應高度的textarea
                
                地址分享:http://www.yijiale78.com/article6/pchsog.html
            
成都網站建設公司_創新互聯,為您提供搜索引擎優化、小程序開發、、品牌網站制作、定制開發、網站設計公司
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯