本文实例为大家分享了JavaScript实现滚动加载更多的具体代码,供大家参考,具体内容如下
vscode
index:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> * {margin:0; padding: 0;} li {list-style: none;} body {background: #eee;} .wrapper {background: #fff;width: 970px; margin:20px auto; padding: 15px;} h1 {text-align: center; border-bottom: 1px solid #ddd; padding-bottom: 20px;} li {margin:20px 0; border-bottom: 1px dotted #eee; padding-bottom: 20px;} p { line-height: 25px;} </style> <script src="/jquery-1.11.3.js"></script></head><body> <div class="wrapper"> <h1>新闻列表(加载更多)<script>document.write(new Date().toLocaleString())</script></h1> <ul> </ul> <div class="footer" style="text-align: center"> <img style="width: 40px" src="" alt=""> </div> </div> <script> let page = 1; // 默认是第1页 let load = true; function getNewsList(page) { $(".footer img").attr("src","/timg.gif") load = false; $.get("/news",{page},res=>{ // console.log(res) if(res.news.length){ let str =""; // 客户端渲染,客户端自己通过ajax获取数据,自已渲染数据 res.news.forEach(item=>{ str += ` <li> <h2><a href="#" rel="external nofollow" >${item.title}</a></h2> <p class="time">${item.time}</p> <p class="summary">${item.summary}</p> </li> ` }) $("ul").append(str) load = true; }else{ $(".footer").html("--------------- 我是有底线的 --------------- ") load = false; } }) } getNewsList(page); // 一上来就获取第1页的数据 // 判断出什么时候到底部 $(document).scroll(function () { let st = $(window).scrollTop(); // 卷上去的高度 let ch = $(window).height(); // 一屏的高度 let dh = $(document).height(); // 整个文档(整个内容)的高度 if((st+ch) >= dh && load){ // 滚动到了底部 getNewsList(++page) } }) </script></body></html>JS:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。