gpt4 book ai didi

javascript - js如何无限滚动到顶部?

转载 作者:太空狗 更新时间:2023-10-29 15:58:35 25 4
gpt4 key购买 nike

有一个无限滚动到底部的例子。

  var $ol = document.querySelector("ol");

function load_more() {
var html = "";

for (var i = 0; i < 5; i++) html += '<li></li>';
$ol.innerHTML += html;
}

$ol.addEventListener("scroll", function() {
if ($ol.scrollHeight - $ol.scrollTop === $ol.clientHeight)
load_more();
});
    <ol>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>


有一个jsfiddle example

除了用 js 置顶之外,如何实现无限滚动?

最佳答案

使用 $ol.scrollTop === 0 您可以检查 ol 是否滚动到顶部。 scollTop 在最上位时始终为 0。

还更改了 loadMore 函数,以便它使用 $ol.prepend(document.createElement('li'))将新元素附加到元素的开头

最后我在 loadmore 函数中添加了 $ol.scrollTop = firstEl.offsetTop; 以自动滚动到之前是第一个元素的元素。

我颠倒了你的OL,这样可以更容易地看到加载了新元素。这当然不是必需的。

var $ol = document.querySelector("ol");

//Call this function onload so new content gets loaded and scrolling upwards become available.
load_more();

//Add event listner that triggers function when the element is scrolled to the top.
$ol.addEventListener("scroll", function() {
if ($ol.scrollTop === 0)
load_more();
});

//Load more items.
function load_more() {
//Get the current first element.
var firstEl = $ol.firstElementChild;

//prepend the new elements.
for (var i = 0; i < 5; i++) {
$ol.prepend(document.createElement('li'))
}

//scroll to the previous first element.
$ol.scrollTop = firstEl.offsetTop;
}
ol {
height: 100px;
overflow: scroll;
}
<ol reversed>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>

关于javascript - js如何无限滚动到顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57606693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com