网站注册申请,中山网站搜索优化,泰安网络安全工程师培训,wordpress 用户角色在使用elementUI组件库的时候#xff0c;用到了无限滚动这个功能。我没有看源码#xff0c;直接在网上学习了下实现的思路#xff0c;然后自己手动编码以下。在此总结下。假设页面上有一个盒子容器#xff0c;容器内有一些子元素。容器的高度是固定的#xff0c;有纵向滚动…在使用elementUI组件库的时候用到了无限滚动这个功能。我没有看源码直接在网上学习了下实现的思路然后自己手动编码以下。在此总结下。假设页面上有一个盒子容器容器内有一些子元素。容器的高度是固定的有纵向滚动条。怎么做到滚动到底部的时候就能触发事件查询数据呢用图形的形式分析下image.png知道思路后我们就是想办法用代码的形式实现它即可。js子元素总高度 scrollHeight可视区域高度 clientHeight滚动条纵向偏移量 scrollTop我把代码贴上来,因为是vue技术栈所以在vue环境开发cdn引入即可。(还有个原因是vue用多了之后原生js操作dom不太会写了尴尬□)无限滚动#div1 {width: 500px;height: 400px;margin: 50px auto;overflow-y: scroll;}.p1 {height: 40px;line-height: 40px;margin: 5px 0;background-color: #409EFF;color: white;font-size: 16px;text-align: center;}#div1::-webkit-scrollbar {/*滚动条整体样式*/width: 10px; /*高宽分别对应横竖滚动条的尺寸*/height: 10px;scrollbar-arrow-color:rgba(0,0,0,0.2);}#div1::-webkit-scrollbar-thumb {/*滚动条里面小方块*/border-radius: 5px;-webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);background: pink;scrollbar-arrow-color:rgba(0,0,0,0.2);}#div1::-webkit-scrollbar-track {/*滚动条里面轨道*/-webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);border-radius: 0;background: white;}new Vue({el: #app,data: {list: []},created() {for (let i 1; i 10; i) {this.list.push(第i条数据);}},methods: {scrollCb() {// 首先找出子元素总高度 scrollHeight// 再找出可视区域高度 clientHeight// 滚动条纵向偏移量 scrollTop// 当 总高 - 可视区域高度 - 纵向偏移量 某个最小阈值 的时候触发无限滚动const dom document.getElementById(div1);const totalHeight dom.scrollHeight;const clientHeight dom.clientHeight;const scrollTop dom.scrollTop;if (totalHeight - clientHeight - scrollTop 20) {this.addList();}},addList() {this.list.push(无限滚动触发);for (let i 1; i 10; i) {this.list.push(第 i 条数据);}}}})上面的样式无所谓啦无非是想做的好看点可能前端都这样吧。效果是这样的每次滚动到列表底部时就会增加列表元素。image.png进阶下在vue中有自定义指令这个鬼东西elementUI提供的无限滚动也是个自定义指令。我试着将其写成自定义指令的形式。样式等都是一样的只是逻辑改了下采用自定义指令实现new Vue({el: #app,data: {list: []},created() {for (let i 1; i 10; i) {this.list.push(第i条数据);}},directives: {infiniteScroll: {bind(el, binding, vNode) {el.onscroll () {const totalHeight el.scrollHeight;const clientHeight el.clientHeight;const scrollTop el.scrollTop;if (totalHeight - clientHeight - scrollTop 20) {vNode.context.addList(); // vNode.context指向当前vue实例}};}}},methods: {addList() {this.list.push(无限滚动触发);for (let i 1; i 10; i) {this.list.push(第 i 条数据);}}}})效果和第一个方法是一样的。(还有用vnode上报事件的方法下次写)这样我就简单实现了一个向下的无限滚动功能。学习一个东西的时候最好自己尝试找解决方法。如果找不到再学习别人的重要的是理解思路而不是死记硬背代码这样才能记得牢固。