修复ChatGPT风格带图标输入框的图标位置偏移问题
固定发送按钮位置的聊天输入框解决方案
问题说明
实现了类似ChatGPT的带图标输入框,当输入内容超过若干行后,右侧的send图标会向上偏移。需求是让图标始终固定在输入框底部初始位置,输入内容增多时输入区域可滚动,图标位置保持不变。
修改方案
核心思路是将发送按钮与输入滚动区域分离,通过布局调整让按钮固定在容器底部,同时确保输入区域在内容过多时可滚动。
修改后的HTML代码
<div class="chat-input-container"> <div class="input-container" ng-class="{'scrollable': shouldShowScroll()}"> <div contenteditable="true" class="input-field" ng-model="setSearchInputValue" ng-keypress="onKeyPress($event)"></div> </div> <md-button class="md-icon-button" ng-disabled="setSearchInputValue.trim().length === 0"> <md-icon md-font-icon="material-icons" ng-disabled="setSearchInputValue.trim().length === 0">send</md-icon> </md-button> </div>
修改后的CSS代码
#input { word-wrap: break-word; } .bg-yellow { background-color: lightyellow; } .bg-green { background-color: #eafef6; } .chat-input-container { position: relative; display: flex; align-items: flex-end; /* 让内部元素底部对齐 */ border: 1px solid #ddd; padding: 5px; bottom: 0; width: 40%; z-index: 1; border-radius: 10px; margin-left: 450px; margin-top: 50px; } .input-container { flex: 1; overflow-y: hidden; max-height: 300px; position: relative; text-transform: capitalize; } .scrollable { overflow-y: auto; } .input-field { min-height: 25px; height: auto; border: none; outline: none; padding: 5px 5px 10px 5px; font-size: 16px; resize: none; width: 100%; line-height: 20px; word-wrap: break-word; text-transform: capitalize; } md-button { min-width: 40px; background-color: #0078D7; color: #fff; margin-left: 6px; } md-button md-icon { font-size: 24px; } md-button:hover { background-color: #005A9E; } .md-button.md-icon-button { margin: 0 6px; height: 40px; min-width: 0; line-height: 24px; padding: 8px; width: 40px; border-radius: 50%; }
关键修改点
- HTML结构调整:将发送按钮从
input-container中移出,放到外层的chat-input-container内,使按钮脱离输入滚动区域的布局影响。 - 容器布局优化:给
chat-input-container设置align-items: flex-end,确保按钮始终对齐容器底部;input-container占据剩余空间,专门处理输入内容的滚动逻辑。 - 输入区域样式调整:修改
input-field宽度为100%,移除不必要的flex属性,避免布局冲突,保证输入区域在容器内充分利用空间。 - 按钮样式简化:移除按钮上的
align-self: flex-end,外层容器的对齐规则已能保证按钮位置稳定。
JS代码(无需修改)
$scope.shouldShowScroll = function () { var inputField = document.querySelector('.input-field'); var lineHeight = parseInt(window.getComputedStyle(inputField).getPropertyValue('line-height')); var maxLines = 8; return inputField.scrollHeight > lineHeight * maxLines; };
内容的提问来源于stack exchange,提问作者Junaid Azhar
相关产品推荐
相关产品推荐

