有的时候,我们会遇到网页中,一切内容只有在分页中才有,但是又需要在当前页面中展示。例如获取分页文章信息实现首页的无限加载效果。
现在就以获取分页文章为例,直接上代码
loadMoreArticles() {
if (!ThemeConfig.enable_index_list_ajax){
return
}
// 在页面加载完成后执行
$(document).ready(() => {
const $domLoadContainer = $(".joe_load_container");
$domLoadContainer.on('click','.joe_load', async function () {
const $domLoad = $(".joe_load");
this.domNext = $domLoad.attr('data-next');
// console.log(this.domNext)
$domLoad.html("加载中...").attr("loading", "true");
fetch(this.domNext, {
method: "GET",
})
.then((response) => response.text())
.then((html) => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const postListElement = document.querySelector(".joe_list");
// console.log(postListElement)
const postListNewElements = doc.querySelectorAll(".joe_list .joe_list__item");
// console.log(postListNewElements)
if (postListNewElements && postListNewElements.length > 0) {
postListNewElements.forEach((element) => {
postListElement.appendChild(element.cloneNode(true));
});
}
const $newDomLoad = $(doc).find(".joe_load");
if ($newDomLoad.attr('data-next') !== '/') {
$domLoadContainer.empty().append($newDomLoad);
} else {
$domLoadContainer.remove();
}
// 向下滚动一段距离
const lastItemTop = postListElement.querySelector(".joe_list__item:last-child").offsetTop;
const scrollTop = lastItemTop - window.innerHeight; // Adjust the value as needed
window.scrollTo({
top: scrollTop,
behavior: 'smooth'
});
})
.catch((error) => {
console.error(error);
})
.finally(() => {
});
});
});
},