怎么做网站上做电子书,小程序开发公司在哪,网页设计流程25,网站开发前端应用程序背景
在日常开发过程中#xff0c;我们会遇到图片懒加载的功能#xff0c;基本原理是#xff0c;滚动条滚动到底部后再次获取数据进行渲染。
那怎么判断滚动条是否滚动到底部呢#xff1f;滚动条滚动到底部触发时间的时机和方法又该怎样定义#xff1f;
针对以上问题我…背景
在日常开发过程中我们会遇到图片懒加载的功能基本原理是滚动条滚动到底部后再次获取数据进行渲染。
那怎么判断滚动条是否滚动到底部呢滚动条滚动到底部触发时间的时机和方法又该怎样定义
针对以上问题我做了以下总结
如何判断滚动条已经滚动到底部
先看一张图片解析
从图中不难看出
滚动条滚动的最大距离父盒子的高度 子盒子的高度
也就是说子盒子的高度-父盒子的高度滚动距离时滚动条触底
那如何获取盒子的高度和滚动距离
大多数情况下子元素的高度是不确定的会随着图片的加载子元素的高度越来越高
我们可以通过
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?spm1001.2014.3001.5501
示例代码
HTML
!DOCTYPE html
html langCH-ENheadmeta charsetutf-8 /meta http-equivX-UA-Compatible contentIEedge,chrome1 /meta nameviewport contentwidthdevice-width /titleflex/title/headbodydiv classcontainerdiv classitem内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容/div/div/body
/html
js
scriptwindow.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
stylebody,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
线上示例
滚动加载线上示例