如何用min-height设置textarea初始高度并保留动态扩展功能?
解决方案:实现textarea初始小高度+动态自适应
问题核心在于textarea默认存在内边距、行高的默认样式,同时原有JS代码未在页面加载时初始化高度,导致min-height设置不生效;直接设height则会被JS的height:auto覆盖,且初始阶段未执行高度调整逻辑。
步骤1:修正CSS样式
重置textarea默认内边距,设置匹配目标初始高度的行高,确保min-height能真正生效:
.finder__input { border: none; resize: none; background-color: red; outline: none; font-size: 15px; letter-spacing: 1px; width: 100%; font-weight: bold; /* 去掉默认上下内边距,避免挤占高度 */ padding: 0; /* 行高与目标初始高度匹配,要20px就改20px */ line-height: 10px; min-height: 10px; max-height: 90px; }
步骤2:完善JavaScript代码
新增页面加载时的高度初始化逻辑,同时优化DOM元素获取方式:
var areaName = "finder__input"; var textarea = document.getElementById(areaName); // 抽离通用高度调整函数 function adjustTextareaHeight(el) { el.style.height = "auto"; el.style.height = el.scrollHeight + "px"; } // 页面加载完成后初始化高度,确保初始显示目标高度 window.addEventListener('load', function() { adjustTextareaHeight(textarea); }); // 输入时动态调整高度 textarea.addEventListener("input", function() { adjustTextareaHeight(this); });
逻辑说明
- 重置
padding:0:消除textarea默认上下内边距对高度的影响,让min-height设置直接作用于内容高度 - 匹配行高:保证单行文本高度与设置的初始高度一致,避免文字溢出或高度冗余
- 初始化执行:页面加载时主动调整高度,解决初始状态下高度不生效的问题
- 动态调整逻辑:每次输入先重置高度为
auto,再用scrollHeight获取内容实际高度,实现自适应扩展
完整修改后代码
HTML(无需改动)
<div class="container"> <div class="finder"> <div class="finder__outer" id="finder__outer"> <textarea id="finder__input" class="finder__input" type="text" name="q" placeholder="Write a message..."></textarea> </div> </div> </div>
CSS
body { color: #292929; background-color: #616f91 } .container { display: flex; flex-direction: row; justify-content: center; position: absolute; bottom: 0; left: 0; right: 0; padding-bottom: 100px; } .finder { border: 1px solid #fff; background-color: #f6f5f0; border-radius: 5px; padding: 3px; box-shadow: 2px 2px 1px black, -1px -1px 1px white; } .finder__outer { position: relative; border-radius: 5px; min-height: 1px; padding: 8px; background-color: transparent; box-shadow: inset 2px 2px 5px -2px black, inset -10px -10px 5px -7px white; } .finder__input { border: none; resize: none; background-color: red; outline: none; font-size: 15px; letter-spacing: 1px; width: 100%; font-weight: bold; padding: 0; line-height: 10px; min-height: 10px; max-height: 90px; }
JavaScript
var areaName = "finder__input"; var textarea = document.getElementById(areaName); function adjustTextareaHeight(el) { el.style.height = "auto"; el.style.height = el.scrollHeight + "px"; } // 初始化高度 window.addEventListener('load', () => adjustTextareaHeight(textarea)); // 输入时动态调整 textarea.addEventListener("input", function() { adjustTextareaHeight(this); });
内容的提问来源于stack exchange,提问作者N G
相关产品推荐
相关产品推荐

