JavaScript实现textarea自适应高度时尺寸异常问题排查
解决方案
问题根源在于TailwindCSS的固定高度类(h-10、min-h-10)与textarea的scrollHeight计算逻辑冲突,加上Firefox的渲染特性导致高度计算偏差。可通过以下步骤修复:
1. 调整TailwindCSS类,移除固定高度约束
去掉h-10和min-h-10,改用自定义最小高度匹配一行内容的高度,同时保留内边距和行高控制:
<textarea id="msgBox" maxlength="1024" class="flex-1 px-3 py-2 text-white rounded-lg border border-black resize-none focus:outline-none box-border leading-normal" style="max-height: 100px; overflow-y: auto; min-height: calc(1em + 1rem);" placeholder="Text here"></textarea>
box-border确保内边距纳入高度计算min-height: calc(1em + 1rem)对应一行文本的高度(1em为行高,1rem是py-2的上下内边距总和)
2. 优化JavaScript高度计算逻辑
添加强制重绘步骤,解决Firefox中scrollHeight计算滞后的问题,同时补充初始化逻辑:
const msgBox = document.getElementById('msgBox'); // 输入时调整高度 msgBox.addEventListener('input', function() { this.style.height = 'auto'; // 强制浏览器重绘,避免计算偏差 void this.offsetHeight; this.style.height = this.scrollHeight + 'px'; }); // 页面加载时初始化高度 window.addEventListener('load', () => { msgBox.style.height = 'auto'; void msgBox.offsetHeight; msgBox.style.height = msgBox.scrollHeight + 'px'; });
3. 保留原有CSS
body { background: black; } textarea { background: darkblue; }
效果说明
修改后,textarea初始高度为一行内容的高度,输入内容时会精准适配实际内容高度,不会出现无故增高的情况,同时在Firefox中也能正常工作。
内容的提问来源于stack exchange,提问作者DaikoGit
相关产品推荐
相关产品推荐

