主頁 > 知識庫 > 做一個能自適應高度的textarea的示例代碼

做一個能自適應高度的textarea的示例代碼

熱門標簽:智能手機 網(wǎng)站建設 硅谷的囚徒呼叫中心 檢查注冊表項 美圖手機 阿里云 使用U盤裝系統(tǒng) 百度競價點擊價格的計算公式

方法

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的高度。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

標簽:煙臺 通遼 黃山 山南 湘潭 湖北 賀州 懷化

巨人網(wǎng)絡通訊聲明:本文標題《做一個能自適應高度的textarea的示例代碼》,本文關鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266