Textarea动态高度调整滚动大小问题



我有一个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>

问题在于您正在侦听如此多的事件,并且当按下单个键时,其中几个事件被触发,因此正在运行的逻辑中存在冲突。

要解决这个问题,只需使用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>

相关内容

  • 没有找到相关文章

最新更新