繁体   English   中英

jQuery-自动扩展textarea无法处理粘贴的输入

[英]jQuery - auto-expanding textarea doesn't handle pasted input

我正在尝试根据输入的文本自动扩展/缩小文本区域。 textarea的指定高度为250px ,并且可以在450px之前自动扩展到overfow: auto使用滚动条overfow: auto插入。 当在文本区域中键入文本时,它可以完美地工作,但是在粘贴大量文本时,它不能正常工作。

在这里查看小提琴: 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> 

我没有在调试中留下任何调试语句,但确实确实正确地在粘贴上触发了该事件,但是即使粘贴的文本非常大, this.scrollHeight计算this.scrollHeight始终约为250px 我猜在paste事件触发时this.scrollHeight尚未更新? 我该如何解决?

这对我有用:

$(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: 在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM