如果您撰写文字,textarea
的尺寸会增加,但是当您删除此文字时,则没有任何反应。如果要删除文本,是否可以动态降低textarea
的高度?
$('textarea').on('input', function() {
var scrollHeight = parseInt($(this).prop('scrollHeight'));
$(this).height(scrollHeight);
});
.OuterDiv
{
width:200px;
height:300px;
border:1px solid #000;
position:relative;
bottom:0;
}
.text
{
resize:none;
width:198px;
height:45px;
max-height:145px;
background-color:rgba(90,90,180,1);
font-size:16px;
font-family:Arial;
overflow-y:auto;
padding:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OuterDiv">
<textarea class="text" placeholder="Write some text..."></textarea>
</div>
答案 0 :(得分:6)
设置height
样式而不是属性,并使用初始高度,以便始终从45px
开始。
$('textarea').on('input', function() {
$(this).css('height', "45px");
$(this).css('height', this.scrollHeight+"px");
});
.OuterDiv
{
width:200px;
height:300px;
border:1px solid #000;
position:relative;
bottom:0;
}
.text
{
resize:none;
width:198px;
height:45px;
max-height:145px;
background-color:rgba(90,90,180,1);
font-size:16px;
font-family:Arial;
overflow-y:auto;
padding:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OuterDiv">
<textarea class="text" placeholder="Write some text..."></textarea>
</div>
答案 1 :(得分:1)
您可以使用带有contentEditable
的div,而不是根据内容对任何脚本的需要自动调整大小:
.OuterDiv
{
width:200px;
height:300px;
border:1px solid #000;
position:relative;
bottom:0;
}
.text
{
resize:none;
width:198px;
min-height:45px;
height:auto;
max-height:145px;
background-color:rgba(90,90,180,1);
font-size:16px;
font-family:Arial;
overflow-y:auto;
padding:0;
}
[contenteditable=true]:empty:before{
content: attr(placeholder);
display: block; /* For Firefox */
color: grey;
}
<div class="OuterDiv">
<div class="text" contentEditable="true" placeholder="Write some text..."></div>
</div>