登录
首页 >  文章 >  前端

ChatGPT风格输入框设计:带图标多行自适应文本框

时间:2026-04-13 11:42:45 360浏览 收藏

本文深入解析了如何打造一个高度还原ChatGPT体验的智能搜索输入框——它不仅支持多行文本自动扩展、平滑高度过渡,更通过绝对定位与CSS变换精准锁定发送图标在任意内容高度下的垂直居中位置,彻底解决传统flex布局中图标随文字增长而偏移、上浮的顽疾;文章提供语义化更强的textarea替代方案、精炼可靠的CSS样式体系,以及可选的防抖式JavaScript动态高度适配逻辑,兼顾兼容性、可维护性与视觉稳定性,是构建现代对话式UI不可或缺的实战指南。

ChatGPT 风格搜索输入框:带固定位置图标的可自适应多行文本框

本文详解如何实现一个类似 ChatGPT 的搜索输入框,支持多行内容自动扩展、图标始终垂直居中对齐,并在内容增长时保持图标位置稳定不偏移。

本文详解如何实现一个类似 ChatGPT 的搜索输入框,支持多行内容自动扩展、图标始终垂直居中对齐,并在内容增长时保持图标位置稳定不偏移。

要打造一个专业、稳定的 ChatGPT 风格搜索输入框(即带右侧发送图标的可编辑多行输入区域),关键在于解决图标随内容滚动而错位的问题。原代码使用 contenteditable="true" + div 模拟输入,虽灵活但布局控制复杂;配合 flex 布局与 align-items: flex-start 后,md-button 的 align-self: flex-end 会导致图标在内容变高时“上浮”——这正是问题根源。

推荐方案:改用 <textarea> + 绝对定位图标(更语义化、更易控制、兼容性更好):

<div class="form-group">
  &lt;textarea 
    id=&quot;search-input&quot; 
    rows=&quot;1&quot; 
    placeholder=&quot;Ask anything...&quot; 
    ng-model=&quot;setSearchInputValue&quot;
    ng-keypress=&quot;onKeyPress($event)&quot;
  &gt;&lt;/textarea&gt;
  <button 
    class="send-icon-btn" 
    ng-disabled="!setSearchInputValue?.trim()"
    ng-click="submitSearch()"
  >
    <md-icon md-font-icon="material-icons">send</md-icon>
  </button>
</div>

配套 CSS(重点修复图标定位与自适应高度):

.form-group {
  position: relative;
  width: 100%;
  max-width: 500px;
}

#search-input {
  width: 100%;
  min-height: 40px;
  max-height: 160px;
  padding: 10px 42px 10px 12px; /* 右侧预留图标空间 */
  font-size: 16px;
  line-height: 1.4;
  border: 1px solid #ddd;
  border-radius: 24px;
  outline: none;
  resize: none;
  box-sizing: border-box;
  overflow-y: hidden;
  transition: height 0.2s ease;
}

/* 自动高度适配(核心) */
#search-input {
  height: auto;
}

.send-icon-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 32px;
  height: 32px;
  min-width: 0;
  padding: 0;
  background: #0078D7;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-icon-btn md-icon {
  font-size: 18px;
  margin: 0;
}

.send-icon-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

? 关键技巧说明:

  • 图标垂直居中:top: 50% + transform: translateY(-50%) 确保无论输入框多高,图标始终居中;
  • 自适应高度:height: auto + min/max-height + overflow-y: hidden,配合 JS 动态调整(见下);
  • 防抖重设高度(可选增强):在 ng-keypress 或 input 事件后调用以下逻辑,避免换行后高度未及时更新:
$scope.adjustTextareaHeight = function() {
  const el = document.getElementById('search-input');
  el.style.height = 'auto';
  el.style.height = (el.scrollHeight) + 'px';
};
// 在模板中绑定:ng-input="adjustTextareaHeight()" 或监听 $scope.$watch

⚠️ 注意事项:

  • 避免对 contenteditable 元素做复杂 Flex 对齐,它本质是内联元素,行为不可预测;
  • 不要给 .input-container 设置 align-items: flex-start 并期望子元素图标“跟随底部”,应主动控制图标定位;
  • 若必须保留 contenteditable 方案,请将图标容器设为 position: absolute 并脱离文档流,同时确保父容器 position: relative。

最终效果:输入框随文字逐行扩展,发送图标始终悬浮于右上角、垂直居中,无跳动、无偏移,符合现代 UI 交互规范。

以上就是《ChatGPT风格输入框设计:带图标多行自适应文本框》的详细内容,更多关于的资料请关注golang学习网公众号!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>