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
每次按键都改变它的高度?
只有当有新的文本行时才会发生这种情况。
解决方案
'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>
推荐阅读
- objective-c - 是否有为 NSEnumerationOptions 指定顺序的选项?
- r - 将长数据框加入整齐的数据框
- ruby-on-rails - 我想为数据库中的所有记录在 created_at 列中添加 4 天。有没有办法在rails控制台中做到这一点?
- android - 如何使用 NFC 将文件从(Windows)PC 发送到 android/ios?
- node.js - Nodejs/Express 无法始终如一地从帖子中检索正文。快速连续多次调用成功
- python - Python Web 服务器没有响应 CORS 请求
- qlikview - 如何从 QlikView 连接 REST API (Java)?
- laravel - 使用 axios 时的 CORS 但使用 curl 可以正常工作
- cryptography - 有没有一种快速的方法可以使 IBM 的 vncipher 指令结果与 Intel 的 mm_aesdec_si128 相同?
- python - pypy3 - 读取 csv 文件时出现 UnicodeDecodeError