textarea在每次按键时更改其高度

时间:2018-09-22 14:42:54

标签: jquery textarea

$('#txstory').on('input', function () {
	$(this).height(this.scrollHeight);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea id='txstory'></textarea>

为什么txstory在每次按键时都改变其高度?

只有当有新的一行文本出现时,它才会发生。

1 个答案:

答案 0 :(得分:0)

'Height()'和'scrollHeight()'不同。

高度不包括填充。

scrollHeigth包括填充,不包括边框或边距。


添加评论,

$('#txstory').on('input', function () {
    $(this).height(this.scrollHeight);
});

此代码表示

如果在$('#txstory')中输入字符,则将$('#txstory')的高度更改为$('#txstory')的scrollHeight。

init $('#txstory')的高度为30px,上下填充为2px。

所以高度是30,scrollHeight是34。

按照自己的方式行事,

    $('#txstory').on('keydown keyup', function () {
    	$(this).height(1).height( $(this).prop('scrollHeight')+12 );
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id='txstory' style='min-height:30px;'></textarea>