动态加载内容的textarea自适应高度时输入触发页面上滚问题求助
问题解决方法
该问题是由于调整textarea自适应高度的逻辑存在缺陷:每次触发高度调整时,先将textarea高度设置为auto的操作会临时缩小textarea的实际高度,浏览器会自动修正滚动位置,导致页面整体上滚,之后再把高度设置为scrollHeight的操作不会回滚这个位置偏移,就会出现你遇到的问题。
修复后的代码
HTML代码
<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>
CSS代码
#myText { resize: none; overflow: hidden; /* 新增属性,避免调整高度的瞬间出现滚动条干扰计算 */ }
JavaScript代码
$(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) { // 调整高度前先保存当前页面的滚动位置 const currentScroll = window.pageYOffset || document.documentElement.scrollTop; // 执行高度调整逻辑 $(this).height("auto").height(this.scrollHeight + "px"); // 回滚到之前的滚动位置,消除偏移 window.scrollTo(0, currentScroll); }).find('textarea').change(); }; textAreaAutoHgt("#container", "#myText"); });
内容的提问来源于stack exchange,提问作者Jagadheesh
相关产品推荐
相关产品推荐

