背景
在日常開發過程中,我們會遇到圖片懶加載的功能,基本原理是,滾動條滾動到底部后再次獲取數據進行渲染。
那怎么判斷滾動條是否滾動到底部呢?滾動條滾動到底部觸發時間的時機和方法又該怎樣定義?
針對以上問題我做了以下總結:
如何判斷滾動條已經滾動到底部
先看一張圖片解析
從圖中不難看出:
滾動條滾動的最大距離+父盒子的高度 = 子盒子的高度;
也就是說子盒子的高度-父盒子的高度>=滾動距離時,滾動條觸底;
那如何獲取盒子的高度和滾動距離
大多數情況下子元素的高度是不確定的,會隨著圖片的加載子元素的高度越來越高,
我們可以通過
elemet.scrollHeight 獲取子盒子的高度;
elemet.scrollTop 獲取滾動距離;
elemet?.clientHeight 獲取父盒子的高度;
參考
【前端 | CSS】盒模型clientWidth、clientHeight、offsetWidht、offsetHeight_好喝的西北風的博客-CSDN博客只讀屬性Element.clientWidth對于內聯元素以及沒有 CSS 樣式的元素為 0;該屬性包括內邊距(padding),但不包括邊框(border)、外邊距(margin)和垂直滾動條(如果存在)offsetWidth 是測量包含元素的邊框 (border)、水平線上的內邊距 (padding)、豎直方向滾動條 (scrollbar)(如果存在的話)、以及 CSS 設置的寬度 (width) 的值。https://blog.csdn.net/weixin_43340372/article/details/132210911?spm=1001.2014.3001.5501
示例代碼
HTML
<!DOCTYPE html>
<html lang="CH-EN"><head><meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /><meta name="viewport" content="width=device-width" /><title>flex</title></head><body><div class="container"><div class="item">內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容</div></div></body>
</html>
js
<script>window.onload = () => {// 基本思路// 滾動體條所能滾動的最大高度 + continer的高度 = 子盒子(item)的高度;const container = document.querySelector(".container");console.dir(container);const item = document.querySelector(".item");container.addEventListener("scroll",() => {// 父盒子的高度const clientHeight = container.clientHeight;// 子盒子的高度(滾動盒子的高度)const scrollHeight = container.scrollHeight;// 滾動的最大距離const scrollHeight_clientHeight = scrollHeight - clientHeight;// 實時滾動距離const scrollTop = container.scrollTop;// 滾動的最大距離小于等于實時滾動距離時,滾動到了底部if(scrollHeight_clientHeight <= scrollTop){console.log("滾動到底部");}})};
</script>
style
<style>body,html {height: 100%;overflow: hidden;margin: 0;padding: 0;}::-webkit-scrollbar {width: 10px;background-color: gray;}::-webkit-scrollbar-thumb {background-color: black;border-radius: 5px;}.container {height: 500px;width: 400px;margin: 100px auto;background-color: rgb(6, 100, 64);border: blue 5px solid;overflow: auto;}.item {height: 800px;width: 200px;margin: 0 auto;color: #fff;line-height: 200px;overflow: hidden;background-color: rgb(235, 77, 77);}
</style>
線上示例
滾動加載線上示例