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

如何实现Bootstrap消息发送textarea的自动调整大小?

实现textarea自动调整高度的两种实用方案

嘿,这个聊天场景里的需求太常见了!结合你现有的Bootstrap代码,我给你两种简单靠谱的实现方式,不用额外引入第三方库就能搞定~

方案一:原生JavaScript实时监听调整

原理很直白:监听textarea的输入事件,把它的scrollHeight(内容实际高度)赋值给自身高度,同时去掉默认滚动条,让它跟着内容自动撑开,内容减少时也能自动收缩回去。

修改后的完整代码如下:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<ul class="list-group">
  <li class="list-group-item">New Message</li>
</ul>
<form>
  <!-- 加个id方便JS获取,同时禁用手动调整高度 -->
  <textarea class="form-control" id="messageInput" style="resize: none; min-height: 40px;"></textarea>
  <button type="submit" class="btn btn-primary mt-2">Send</button>
</form>

<script>
const messageInput = document.getElementById('messageInput');

// 定义调整高度的核心函数
function adjustTextareaHeight() {
  // 先重置高度为auto,避免内容减少时高度不收缩
  messageInput.style.height = 'auto';
  // 再设置为内容实际高度,确保不会出现滚动条
  messageInput.style.height = messageInput.scrollHeight + 'px';
}

// 页面加载时初始化一次(如果有默认内容的话)
adjustTextareaHeight();

// 监听输入事件,实时调整高度
messageInput.addEventListener('input', adjustTextareaHeight);
// 监听窗口 resize,避免窗口变化时高度异常
window.addEventListener('resize', adjustTextareaHeight);
</script>

方案二:纯CSS实现(简单但有局限性)

如果你的需求对“内容减少时自动收缩”要求不高,也可以用纯CSS搞定,优点是不用写JS,但内容减少后高度不会自动缩回去:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<ul class="list-group">
  <li class="list-group-item">New Message</li>
</ul>
<form>
  <textarea class="form-control" style="resize: none; min-height: 40px; max-height: 200px; overflow-y: auto;"></textarea>
  <button type="submit" class="btn btn-primary mt-2">Send</button>
</form>

这种方式会在内容超过最小高度时自动撑开,直到达到最大高度后显示滚动条,适合对交互要求不那么精细的场景。

小提醒

  • 设置resize: none是为了避免用户手动调整高度,破坏自动调整的逻辑;
  • 方案一里的min-height可以根据你的设计需求调整,比如设成适合一行文字的高度;
  • 如果用方案一,在表单提交后清空textarea时,记得调用一次adjustTextareaHeight(),让它回到初始高度哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:02:59