用最简单方式实现输入框自适应、网上文章我都看了 都不的要点、实现起来很麻烦、由于业务需要实现im聊天输入框,所以按自己想法做一个自适应高度的输入框。
我们用textarea 来实现 , 不考虑用div可编辑的方式,毕竟语义不同 ,首先我们用一个容器来装textarea
这是实现的gif图
上代码!
<div class="input-panel">
<textarea class="input-message"
autoHeight="true"
placeholder="请输入消息"
@keyup="autoHeight($event)"
maxlength="1024"
/>
</div>
css
.input-panel{
width: 75%;
background-color: #ffffff;
padding:8px 10px;
margin-right: 10px;
display: flex;
justify-content: center;
align-items: center;
}
.input-message {
width: 100%;
color: #000000;
height: 20px;
line-height: 20px;
max-height: 85px;
border: 0;
border-radius: 3px;
resize: none;
outline: none;
font-size: 14px;
overflow-y: hidden;
-webkit-appearance: none;
}
js
autoHeight(e){
const send = document.querySelector('.input-message');
const rows = e.target.value.split('\n').length - 1;
send.style.height = 20 * (rows+1) + 'px';
}