1、textarea实现自适应文本框
此方法是利用输入textarea的同时将内容同时注入span之中并将外部div撑起来,textarea自然100%高度自适应高度。需要确保span和textarea的字体样式以及padding保持一致。 点击查看demo
HTML:
<div class="g-table-textarea">
<span id="eleSpan"></span>
<textarea id="eleArea"></textarea>
</div>
CSS:
.g-table-textarea{
/*利用span内容自动撑起最外部div高度,textarea则高度100%自适应高度*/
position: relative;
border: 1px solid;
min-height: 60px;/*保持最小高度*/
width: 50px;
span{
font-family: inherit;
word-break: break-word;
line-height: inherit;
color: #666;
display:block;
font-size: inherit;
padding: 5px;
}
textarea{
font-family: inherit;
position: absolute;
box-sizing: border-box;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding: 5px;
font-size: inherit;
color: inherit;
line-height: inherit;
resize:none;
overflow:hidden;
word-break: break-word;
border: 0 none;
}
}
JS:
const eleArea = document.getElementById('eleArea');
const eleSpan = document.getElementById('eleSpan');
if (eleArea && eleSpan) {
eleArea.addEventListener('input', function (e) {
eleSpan.innerText = e.target.value;
});
}
2、div实现自适应文本框
此方法是利用div的contenteditable,使div元素变为可输入,缺点是网页可读性变差,表单功能无法使用。 点击查看demo
HTML:
<div class="blockcontent" contenteditable="true"></div>
CSS:
.blockcontent{
width:60px;
min-height:60px;
border:1px solid #ccc;
margin:100px auto;
padding:10px;
}