开始我以为直接textarea100%啥的,没啥难度,后面才发现没这么简单,直接整不可行。下面列举两个方法
纯css
<div class="page-chat-ai-textarea-wrapper">
<textarea
class="page-chat-ai-textarea"
v-model="prompt"
placeholder="请在此输入您的问题"
rows="1"
></textarea>
<div class="textarea-visibility">{{ prompt }}</div>
</div>
.page-chat-ai-textarea-wrapper {
min-height: 36px;
max-height: 150px;
width: 100%;
position: relative;
}
.page-chat-ai-textarea {
padding: 6px 8px;
border: none;
outline: none;
resize: none;
width: 100%;
color: inherit;
background-color: transparent;
position: absolute;
width: 100%;
height: 100%;
line-height: 1.5;
font-size: 16px;
overflow: auto;
}
.textarea-visibility {
position: relative;
visibility: hidden;
word-break: break-all;
line-height: 1.5;
height: 100%;
padding: 6px 8px;
}
原理:大概是上面这个写法,原理是通过里面的隐藏一个text来撑开高度
优点:基本css就行
缺点:会晃动,因为输入后,页面text才撑开。不太介意这点晃动的可以。
js(推荐,gpt同款体验)
<textarea
ref="inputrRef"
class="page-chat-ai-textarea"
v-model="prompt"
@input="autoResize"
></textarea>
autoResize() {
const textarea = this.$refs.inputrRef;
if (!textarea) return
textarea.style.height = "auto"; // 重点,这样才能删除的时候变小
textarea.style.height = textarea.scrollHeight + 'px';
},
.page-chat-ai-textarea {
padding: 6px 8px;
border: none;
outline: none;
resize: none;
width: 100%;
color: inherit;
background-color: transparent;
min-height: 24px;
max-height: 600px;
width: 100%;
height: 100%;
line-height: 1.5;
font-size: 16px;
overflow: auto;
}
原理:输入的时候去看scrollheight,并且设置为高度即可。
优点:响应及时,体验极好
缺点:可能吃点性能?问题不大