繁体   English   中英

当我将新元素添加到顶部时,如何将位置保持在可滚动列表中?

[英]How can I keep the position inside a scrollable list when I add new elements to the top?

当我使用 jQuery 的prepend()函数向我的可滚动列表添加一些元素并且我最初位于列表顶部时,列表会自动滚动到第一个添加元素的顶部并且不保留位置。 我怎样才能防止这种情况?

这是我的代码示例,显示了我的问题:

 jQuery(document).ready(function($) { $("button").click(function() { [1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function() { $("div").prepend("<span class='new'></span>"); }); }); });
 div { border: 1px solid; width: 200px; height: 350px; overflow-y: scroll; overflow-x: hidden; } span { height: 40px; width: 200px; display: block; background: gray; } span.new { background: red !important; } span:nth-child(odd) { background: lightgray; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div> <button>Prepend elements</button>

如果您想保持滚动位置,您可以跟踪 div 的 scrollTop 位置和 scrollHeight,然后使用 scrollTop – 如:

 jQuery(document).ready(function($) { $("button").click(function() { let $div = $("div"); let top = $div.scrollTop(); let scrollHeight = $div.prop("scrollHeight"); [1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function() { $div.prepend("<span class='new'></span>") }); $div.scrollTop(top + $div.prop("scrollHeight") - scrollHeight); }); });
 div { border: 1px solid; width: 200px; height: 350px; overflow-y: scroll; overflow-x: hidden; } span { height: 40px; width: 200px; display: block; background: gray; } span.new { background: red !important; } span:nth-child(odd) { background: lightgray; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div> <button>Prepend elements</button>

暂无
暂无

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

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