TextArea根据内容自动调整大小

时间:2015-01-07 21:25:09

标签: jquery html css

所以,我有一个<textarea>作为表单的一部分,用户将输入一个列表项。我决定尝试使用一些jQuery来扩展空间填充时<textarea>的高度。我已经让它以基本形式工作,但我似乎遇到了一个问题,即每次调用keyup()事件时,<textarea>的高度都会增加,而不是内容为填补它。这是我的代码:

HTML:

<textarea class="list_header_itemInput" placeholder="Enter an item..."></textarea>

我的CSS:

.list_header_itemInput {
    width: calc(100% - 36px);
    line-height: 18px;
    resize: none;
    max-height: 180px;
}

最后,我的jQuery:

$('.list_header_itemInput').keyup(function() {
    $(this).css({ height: ($(this).height() + 2) });
});

我需要在代码中更改哪些内容才能获得预期的结果?

2 个答案:

答案 0 :(得分:2)

也许你可以使用弹性js?:http://jsfiddle.net/janjarfalk/r3Ekw/ 并将此插件插入到您的html doc

<script src="http://jquery-elastic.googlecode.com/svn/trunk/jquery.elastic.source.js"></script>

答案 1 :(得分:2)

您可以将textarea的高度设置为1px,然后测量scrollHeight(滚动条表示的像素数)。然后将textarea的高度设置为(scrollHeight + 1)。

$('.list_header_itemInput').keyup(function() { 
    this.style.height = "1px";
    this.style.height = (this.scrollHeight + 1) + "px";
});
相关问题