對于分頁需求,分頁數據的請求觸發十分重要,監聽滑動到底的觸發也有很多種。
1.IntersectionObserver監聽
IntersectionObserver 接口(從屬于 Intersection Observer API)提供了一種異步觀察目標元素與其祖先元素或頂級文檔視口(viewport)交叉狀態的方法。其祖先元素或視口被稱為根(root)。
由MDN文檔可知,IntersectionObserver可以觀察目標元素和父元素可視區域的重疊部分,即可以判斷一個元素是否進入可視區域中。
所以可以在分頁列表尾部,增加一個占位的被觀察元素,當被觀察的元素進入父元素可視區域,就是已經滾動到列表容器底部了。同時IntersectionObserver的異步觀察可以在需要的時候觸發回調執行。
例子:
<ul class="dataList"><button class="bottomnBtn">到底的介紹</button></ul><script>var page = 1, pageSie = 20;const obverseBottn = new IntersectionObserver((entries) => {// intersectionRatio 為 0,則目標在視野外,if (entries[0].intersectionRatio <= 0) return;getPaginationData()page += 1;})obverseBottn.observe(document.querySelector(".bottomnBtn"));function getPaginationData(){let fragme = new DocumentFragment();let bottomnBtn = document.querySelector(".bottomnBtn")for (let i = (page - 1) * pageSie; i < page * pageSie; i++) {let li = document.createElement('li');li.innerHTML = i;fragme.append(li);}bottomnBtn.parentNode.insertBefore(fragme, bottomnBtn)}</script>
.dataList {width: 300px;height: 800px;border: 5px solid black;margin: 0 auto;overflow-y: scroll;list-style: none;}.dataList li {height: 50px;background-color: aquamarine;margin: 10px 0;}.bottomnBtn {width: 100%;height: 50px;background-color: transparent;}