国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > HTML5 > 正文

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

2024-09-05 07:23:01
字體:
來源:轉載
供稿:網友

方法

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 保康县| 宝丰县| 龙口市| 新乐市| 灵山县| 襄樊市| 阳信县| 建德市| 丹凤县| 古蔺县| 霍州市| 吉隆县| 玉龙| 调兵山市| 宜春市| 湄潭县| 陆良县| 万载县| 青浦区| 清河县| 周至县| 平山县| 东源县| 福建省| 阿克陶县| 彭泽县| 平罗县| 阳泉市| 扎赉特旗| 咸丰县| 五常市| 浮梁县| 石棉县| 澄江县| 海盐县| 泰安市| 隆子县| 格尔木市| 北票市| 临沂市| 郑州市|