Textarea动态高度调整大小滚动问题
Posted
技术标签:
【中文标题】Textarea动态高度调整大小滚动问题【英文标题】:Textarea dynamic height resize scrolling issue 【发布时间】:2021-11-26 11:27:14 【问题描述】:我有一个textarea
字段,它可以在没有滚动条的情况下动态加载数据。如果内容太大,如果我尝试在textarea
的末尾键入,页面会向上滚动。请帮忙。
$(document).ready(function()
var data = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32";
$("#myText").val(data);
var textAreaAutoHgt = function(parentId, elementId)
console.log(elementId);
$(parentId).on('change keyup keydown paste cut', elementId, function(e)
$(this).height("auto").height(this.scrollHeight + "px");
).find('textarea').change();
;
textAreaAutoHgt("#container", "#myText");
);
#myText
resize: none;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="container">
<textarea id="myText">Hello!</textarea>
</div>
【问题讨论】:
【参考方案1】:问题是因为您正在侦听太多事件,并且当按下单个键时会触发其中几个事件,因此正在运行的逻辑存在冲突。
要解决此问题,只需使用input
事件。这会在您列出的所有相同事件下触发并避免冲突:
$(document).ready(function()
var data = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32";
$("#myText").val(data);
var textAreaAutoHgt = function(parentId, elementId)
$(parentId).on('input', elementId, function(e)
$(this).height("auto").height(this.scrollHeight + "px");
).find('textarea').trigger('input');
;
textAreaAutoHgt("#container", "#myText");
);
#myText
resize: none;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="container">
<textarea id="myText">Hello!</textarea>
</div>
【讨论】:
太棒了!它正在工作!非常感谢:-) 没问题,很高兴为您提供帮助以上是关于Textarea动态高度调整大小滚动问题的主要内容,如果未能解决你的问题,请参考以下文章
JavaFX TextArea - 调整大小时不需要的滚动条