首页 > 解决方案 > 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每次按键都改变它的高度?

只有当有新的文本行时才会发生这种情况。

标签: jquerytextarea

解决方案


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

高度不包括填充。

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


添加评论,

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

这段代码意味着

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

init$('#txstory')的高度是 30px 并且上下有 2px 的填充。

所以高度是 30,滚动高度是 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>


推荐阅读