我正在尝试根据输入的文本自动扩展/收缩文本区域。文本区域的指定高度为 250px
,并且可以在 overfow: auto
开始滚动条之前自动扩展到 450px
。在文本区域中输入文本时效果很好,但在粘贴大量文本时效果不佳。
在这里查看 fiddle :https://jsfiddle.net/ynv6yta8/1/
还有一个片段:
// auto-expand/shrink text area
$('#mytextarea').bind('input propertychange paste', function() {
var oldHeight = parseInt($(this).height());
if (this.scrollHeight < 450) {
$(this).height(0).height(this.scrollHeight);
}
}).change();
#mytextarea {
height: 250px;
width: 450px;
min-height: 250px;
min-width: 450px;
resize: none;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="mytextarea"></textarea>
我没有在 fiddle 中留下任何调试语句,但事件确实在粘贴时正确触发,但 this.scrollHeight
总是评估为大约 250px
,即使粘贴的文本非常大。我猜 this.scrollHeight
在 paste
事件被触发时还没有更新?我该如何解决这个问题?
最佳答案
这对我有用:
$(document).on("input", "textarea", function()
{
$(this).prop('style').cssText = 'height:auto;';
$(this).prop('style').cssText = 'height:' + $(this).prop('scrollHeight') + 'px';
});
CSS:
textarea
{
resize:none;
max-height:450px;
min-height:250px;
}
灵感来自 https://codepen.io/vsync/pen/czgrf
jsfiddle:Here
关于javascript - jQuery - 自动扩展的文本区域不处理粘贴的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46980299/