如何实现textarea文本溢出时自动切换多行(仿WhatsApp/Telegram)
实现仿WhatsApp/Telegram的自适应高度文本输入框
要实现默认一行、内容溢出时自动扩展到两行/三行、内容减少时自动收缩的textarea,不能靠字符数统计(你已经意识到字符宽度差异的问题),正确的做法是利用textarea的scrollHeight属性结合CSS限制来动态调整高度,以下是具体实现方案:
核心思路
直接通过浏览器计算的内容实际高度(scrollHeight)来调整textarea的高度,同时用CSS限定最小(一行)和最大(三行)高度,避免无限制扩展。
1. HTML结构
<textarea id="chatInput" placeholder="输入消息..."></textarea>
2. CSS样式配置
#chatInput { box-sizing: border-box; width: 100%; padding: 8px 12px; font-family: Arial, sans-serif; font-size: 16px; line-height: 1.5; /* 行高,用于计算最小/最大高度 */ border: 1px solid #e0e0e0; border-radius: 24px; resize: none; /* 禁止用户手动调整大小 */ overflow-y: hidden; /* 初始隐藏滚动条 */ /* 最小高度:1行文本 + 上下内边距 */ min-height: calc(1.5em + 16px); /* 最大高度:3行文本 + 上下内边距 */ max-height: calc(4.5em + 16px); }
3. JavaScript逻辑实现
const textarea = document.getElementById('chatInput'); // 初始化高度,适配初始状态(比如placeholder) const resetHeight = () => { textarea.style.height = 'auto'; const computedStyle = window.getComputedStyle(textarea); const minHeight = parseFloat(computedStyle.minHeight); const maxHeight = parseFloat(computedStyle.maxHeight); let newHeight = textarea.scrollHeight; // 限制高度在最小和最大值之间 if (newHeight < minHeight) { newHeight = minHeight; } else if (newHeight > maxHeight) { newHeight = maxHeight; textarea.style.overflowY = 'auto'; // 超过3行时显示滚动条 } else { textarea.style.overflowY = 'hidden'; } textarea.style.height = `${newHeight}px`; }; // 初始化执行一次 resetHeight(); // 监听输入事件,实时调整高度 textarea.addEventListener('input', resetHeight); // 监听窗口 resize,确保宽度变化时高度正确 window.addEventListener('resize', resetHeight);
关键细节说明
scrollHeight:textarea的这个属性会返回内容实际占据的高度(包含内边距),完全不受字符宽度差异影响,是最准确的内容高度计算方式。- 每次调整前先设
height: auto:避免之前的高度限制浏览器重新计算内容高度。 - 滚动条控制:当内容超过3行时,固定高度并显示滚动条,保持输入框布局稳定;内容减少到3行以内时,自动隐藏滚动条并收缩高度。
内容的提问来源于stack exchange,提问作者b3rry
相关产品推荐
相关产品推荐

