我正在使用 waypoint.js 库来检测用户何时滚动到 ul 的底部。然后这会触发对我的服务器的 axios 调用,返回一个 html 字符串。我正在使用模板标签从该字符串创建元素,删除一些元素,然后将这些元素附加到 ul。我一直遇到的问题只发生在移动设备上。在我附加这些元素并将 scrollTop 设置为用户在附加之前滚动到的位置之后,滚动条会跳到顶部。
我曾尝试使用 setTimeout() 来停止 scrollTop 的设置,这很有效,但是您可以看到 scrollTop 从 0 跳到保存的值,这是非常难看的。
容器:
<ul id="container" style="overflow-y: scroll;" >
{% include 'myapp/items.html' %}
</ul>
项目:
{% if content.has_previous %}
<li class="loadPrev" id="loadPrev-{{content.previous_page_number}}" onclick="getPrevRows('{{ some_variable }}','{{ content.previous_page_number }}');">
</li>
{% endif%}
{% for item in content %}
<li> nested stuff </li>
{% endfor %}
{% if content.has_next %}
<li class="loadMore" id="loadMore-{{content.next_page_number}}" onclick="getMoreRows('{{ bookdetails.url }}', '{{ content.next_page_number }}');">
</li>
{% endif %}
Javascript:
function getMoreRows(some_variable, page) {
# destroy current waypoints so they dont get triggered again on append
waypoint.destroyAll()
axios.get(`my_view_url/?page=${page}`).then((res) => {
let container = document.getElementById('container');
let template = document.createElement('template');
template.innerHTML = res.data;
let elements = template.content;
let children = Array.from(container.children);
let loadMoreLi = children[children.length - 1];
let scrollTop = container.scrollTop;
let loadPrevLink = elements.getElementById(`loadPrev-${Number(page) - 1}`);
if (loadPrevLink) {
elements.removeChild(loadPrevLink)
}
container.append(elements); // append the returned html
container.removeChild(loadMoreLi);
container.scrollTop = scrollTop;
// create new waypoints with newly appended loadMore and loadPrev lis
loadPrev = createLoadPrev();
loadMore = createLoadMore();
});
}