需求
输入框输入换行时,像微信一样高度向上扩展
效果图
输入前
输入后
源码
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0,user-scalable=0" />
<style>
body, html{
margin: 0;
}
.box{
width: 100vw;
height: 100vh;
display: flex; /* 外框使用列方向的流布局 */
flex-direction: column;
}
.box > .head{
width: 100%;
flex: 0 0 100px; /* 等同于width: 100px 固定高度,不分享父组件的剩余高度 */
background: black;
}
.box > .history{
width: 100%;
flex: 1; /* 消息部分独占父级剩余高度,底部输入框高度发生改变,这部分会自动缩小 */
background: blue;
}
.box > .inputBox{
height: max-content; /* 根据内容变化高度 */
display: flex;
padding: 8px;
box-sizing: border-box;
margin-bottom: 100px;
}
/* 输入框式样 因为使用的div替代textarea所以需要自己修改一些式样向原生textarea靠齐
如果可以建议使用现有的框架里的自适应高度输入框代替
# 输入框高度自适应部分引用自文章 https://blog.youkuaiyun.com/HelloMyCode/article/details/85292056
*/
.box > .inputBox > .input{
width: 200px;
border: 1px solid black;
border-radius: 6px;
min-height: 24px; /* 最低高度 */
max-height: 100px; /* 最高高度 */
overflow-y: hidden;
}
</style>
</head>
<body>
<div class="box">
<div class="head"></div>
<div class="history"></div>
<div class="inputBox">
<div class="inputBefore">前</div>
<div class="input" contenteditable="true"></div>
<div class="inputAfter">后</div>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
// const sleep = timeout=> new Promise((a,b)=>{
// setTimeout(function() {
// a();
// }, timeout);
// })
// async function init(){
// for(var i = 0; i < 10; i++){
// await sleep(1000);
// var $input = $("#input");
// console.log($input.height())
// $input.height($input.height() + 20);
// }
// };
// init();
</script>
</html>