[英]How can I keep the position inside a scrollable list when I add new elements to the top?
When I add some elements to my scrollable list with jQuery's prepend()
function and I'm initially at the top of the list, the list automatically scrolls to the top of the first added element and doesn't keep the position.当我使用 jQuery 的
prepend()
函数向我的可滚动列表添加一些元素并且我最初位于列表顶部时,列表会自动滚动到第一个添加元素的顶部并且不保留位置。 How can I prevent this?我怎样才能防止这种情况?
This is my code example showing my problem:这是我的代码示例,显示了我的问题:
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>
If you want to maintain the scroll position you can track the scrollTop position and scrollHeight of the div then use scrollTop – like:如果您想保持滚动位置,您可以跟踪 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.