You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为自动增高的textarea设置高度上限

解决textarea高度超出父容器max-height的问题

要实现类似ChatGPT输入栏的效果——textarea随内容自动增高,达到父容器最大高度后停止扩展并显示滚动条,可以通过修改输入事件逻辑实现,同时保留textarea的placeholder功能。

修改后的代码

<div class="overflow-hidden resize-none w-full max-w-full flex flex-col-reverse" style="max-height: 200px;">
  <!-- 父容器的max-height根据各页面需求自定义 -->
  <textarea
    id="content"
    rows="1"
    class="min-h-full bg-white rounded shadow px-6 py-4 w-full max-w-full resize-none"
    placeholder="Type here..."
    oninput="autoResize(this)"
    style="overflow: hidden;"
  ></textarea>
</div>

<script>
function autoResize(textarea) {
  // 重置textarea高度,获取真实内容高度
  textarea.style.height = '';
  const scrollHeight = textarea.scrollHeight;
  
  // 获取父容器的计算样式,计算textarea可用最大高度
  const parent = textarea.parentElement;
  const parentStyle = window.getComputedStyle(parent);
  const parentMaxHeight = parseFloat(parentStyle.maxHeight);
  const parentPaddingTop = parseFloat(parentStyle.paddingTop);
  const parentPaddingBottom = parseFloat(parentStyle.paddingBottom);
  const availableMaxHeight = parentMaxHeight - parentPaddingTop - parentPaddingBottom;
  
  // 判断是否超出高度上限
  if (scrollHeight > availableMaxHeight) {
    textarea.style.height = availableMaxHeight + 'px';
    textarea.style.overflowY = 'auto';
  } else {
    textarea.style.height = scrollHeight + 'px';
    textarea.style.overflowY = 'hidden';
  }
}

// 页面加载时初始化高度
document.addEventListener('DOMContentLoaded', () => {
  const textarea = document.getElementById('content');
  textarea && autoResize(textarea);
});
</script>

关键逻辑说明

  • 重置高度:每次输入时先清空textarea的行内高度,确保scrollHeight能准确反映内容实际高度。
  • 计算可用高度:通过getComputedStyle获取父容器的max-height,扣除父容器的上下内边距,得到textarea可使用的最大高度。
  • 高度控制:内容高度未超限时,自适应高度并隐藏滚动条;超出上限时,固定高度并显示垂直滚动条。
  • 初始化处理:页面加载时自动执行一次高度计算,避免初始状态高度异常。

注意事项

  • 父容器必须明确设置max-height,建议将父容器overflow设为hidden,避免父容器自身出现滚动条。
  • 若父容器存在边框或额外间距,需在计算availableMaxHeight时相应扣除对应数值,保证高度计算准确。

内容的提问来源于stack exchange,提问作者Lars Lagauw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 15:55:12