国产探花免费观看_亚洲丰满少妇自慰呻吟_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的高度。

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 富蕴县| 凉城县| 阿坝县| 平遥县| 广安市| 桂阳县| 兴宁市| 黄平县| 永年县| 洞口县| 抚远县| 博兴县| 托克逊县| 白水县| 临泉县| 安乡县| 东安县| 旌德县| 仙居县| 南平市| 绥中县| 台中县| 阳江市| 同德县| 仙游县| 桑植县| 常德市| 文昌市| 武定县| 蓝山县| 新密市| 嫩江县| 呼玛县| 广灵县| 库伦旗| 社会| 资溪县| 玉龙| 柳江县| 宝兴县| 大新县|