原生JS实现页面滚动到底部时自动加载数据效果

        在我们日常开发中为了避免一次性数据加载量过大,而导致页面加载缓慢,运行卡顿。通常会使用懒加载进行按需加载,在提高项目运行流畅度的同时也可以增加用户体验。懒加载有很多场景很多方式,那么今天就教大家如何一个原生js实现页面懒加载的方式,也就是当滚动到页面最底部时会触发回调去请求数据。

        当原生的理解后,对于我们后续使用框架开发的遇到类似情况也会更加容易变通和实现。


看代码

引入Axios

<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.min.js"></script>

CSS部分

<style>
        * {
            padding: 0;
            margin: 0 auto;
            list-style: none;
            transition: all 0.5s ease;
        }

        body {
            background-color: #475164;
            background-image: url(http://zhongguose.com/img/texture.png);
            padding-bottom: 50px;
        }

        h2 {
            text-align: center;
            margin: 20px 0;
        }

        .row {
            width: 1290px;
        }

        .list_contrant {
            width: 100%;
            overflow: hidden;
        }

        .cidPage_Separate {
            width: 300px;
            height: 400px;
            /* background-color: aqua; */
            background-color: white;
            margin-right: 30px;
            margin-bottom: 30px;
            border-radius: 10px;
            padding: 0 15px;
            box-sizing: border-box;
            float: left;
        }

        .cidPage_Separate:hover {
            transform: translateX(-5px) translateY(-5px);
            -webkit-box-shadow: 6px 6px 13px -2px rgba(0, 0, 0, 0.7);
            -moz-box-shadow: 6px 6px 13px -2px rgba(0, 0, 0, 0.7);
            box-shadow: 6px 6px 13px -2px rgba(0, 0, 0, 0.7);
            cursor: pointer;
        }

        .cidPage_Separate:nth-child(4n) {
            margin-right: 0;
        }

        .groundFloor_imgUrl {
            height: 170px;
            margin-top: 15px;
            overflow: hidden;
            border-radius: 8px;
        }

        .groundFloor_imgUrl img {
            width: 100%;
            height: 100%;
        }

        .hero_name {
            height: 40px;
            line-height: 40px;
            margin: 15px 0;
            font-size: 20px;
            font-weight: 700;
        }

        .hero_introduce {
            height: 125px;
            line-height: 22px;
            margin-bottom: 20px;
        }

        .base_Anime {
            width: 100%;
            height: 50px;
            /* background-color: aqua; */
            position: relative;
            display: none;
            /* visibility: visible; */
        }

        .Loading_animation {
            display: block;
            width: 30px;
            height: 30px;
            /* background-color: #475164; */
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translateX(-50%) translateY(-50%);
            background-image: url("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01ccee5cf75dc1a801205e4b392210.gif&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1670245718&t=3f172a26acf6f2d501151ac5b63d45da");
            background-size: 300%;
            background-position: center center;
        }

        h6 {
            text-align: center;
            display: none;
        }
    </style>

HTML+Javascript部分

<body>
    <h2>王者英雄列表</h2>
    <div class="row">
        <ul class="list_contrant">
        </ul>
        <div class="base_Anime">
            <i class="Loading_animation"></i>
        </div>
        <h6>暂无更多数据</h6>
    </div>

    <script>
        const General = document.querySelector(".list_contrant"); // 获取ul
        const base_Anime = document.querySelector(".base_Anime"); // 获取加载元素
        const noData = document.querySelector("h6");              // 暂无数据
        let requestNumeric = 1; // 每次请求数据的id值
        let jointSum = ""; // li内容

        async function getHeroInfo(requestNumeric) {
            let data = (await axios({
                method: "get",
                url: `http://localhost:3000/posts/${requestNumeric}` // ${requestNumeric} 请求数据的id
            })).data
            data.data.forEach(element => {
                jointSum +=
                    `
                        <li class="cidPage_Separate ">
                            <div class="groundFloor_imgUrl">
                                <img src=${element.img_url} alt="">
                            </div>
                            <div class="hero_name">${element.hero_name}</div>
                            <p class="hero_introduce"><b>英雄台词:</b>${element.hero_introduce}</p>
                        </li>
                    `
            });
            General.innerHTML = ""; // 先将原来的ul中内容置空
            General.innerHTML = jointSum; // 加入新的内容
            base_Anime.style.display = "none"; // 将动画元素隐藏
        }
        getHeroInfo(1); // 第一次加载时默认调用一次
        let flat = true; // 设置节流的开关阀门
        window.addEventListener("scroll", () => { // 监听浏览器窗口滚动
            if (requestNumeric > 6) { // 请求id大于6时已经没有数据,则停止请求
                base_Anime.style.display = "none"; // 关闭 -- 加载动画
                noData.style.display = "block"; // 打开 -- 暂无数据文字
                return;
            };
            if (General.getBoundingClientRect().bottom < document.documentElement.clientHeight) { // 当页面主元素底部到浏览器顶部高度位置小于浏览器总高度
                if (!flat) return; // 节流 -- 判断阀门是否开着
                flat = false; // 进来后关闭阀门
                setTimeout(() => {
                    requestNumeric++; // 增加下次请求的id
                    getHeroInfo(requestNumeric); // 调用请求数据的函数
                    flat = true; // 每过1秒开启一次阀门(允许请求加载数据)
                }, 1000)
                base_Anime.style.display = "block"; // 显示加载动画
            }
        })
    </script>
</body>

看效果


总结以下知识重点

getBoundingClientRect() 获取当前元素在页面中的所有距离信息

  1. bottom:对象底部距离浏览器当前可视顶部的距离
  2. height: 该对象的高度
  3. left: 对象距离浏览器可视最左侧的距离
  4. right: 对象距离浏览器可视最右侧的距离
  5. Top: 对象顶部距离当前浏览器可视顶部的距离
  6. width: 当前对象宽度
  7. x: 对象左侧距离浏览器可视左侧距离
  8. y: 对象顶部距离浏览器可视顶部水平
General.getBoundingClientRect().bottom // 获取元素底部到浏览器顶部的距离
< document.documentElement.clientHeight // 获取浏览器高度
// 当页面主元素底部到浏览器顶部高度位置小于浏览器总高度,则触发回调去加载数据

看图更能理解滚动距离监听

        如果没有接口的也阔以看我上一篇json-serve的介绍,可以自己写一个小的数据库接口供测试使用,以上的数据便是使用json-serve写的,非常方便且利于理解。

 希望能够有所帮助!

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现列表内容自动向上滚动效果,可以使用原生的JavaScript来操作DOM元素和定器。 首先,可以通过getElementById或querySelector等方法获取到包含列表内容的元素。 然后,通过获取元素的高度、内容等信息来判断是否需要滚动。 接着,可以利用定器setInterval来不断改变元素的scrollTop属性值,实现滚动效果。 具体步骤如下: 1. 首先,获取到包含列表内容的元素: ```javascript var listContainer = document.getElementById("listContainer"); //或者使用querySelector根据CSS选择器选择元素: var listContainer = document.querySelector("#listContainer"); ``` 2. 判断是否需要滚动,比如当元素内容的高度大于元素本身的高度才需要滚动: ```javascript if(listContainer.scrollHeight > listContainer.clientHeight){ // 需要滚动,执行后续操作 } ``` 3. 设置定器,不断改变元素的scrollTop属性值,实现滚动效果: ```javascript var isScrolling = true; // 表示是否正在滚动 setInterval(function(){ if(isScrolling){ listContainer.scrollTop += 1; // 每次滚动1个像素,可根据需要调整滚动速度 if(listContainer.scrollTop === (listContainer.scrollHeight - listContainer.clientHeight)){ listContainer.scrollTop = 0; // 滚动底部后,回到顶部 } } }, 50); // 每50毫秒滚动一次,可根据需要调整滚动速度 ``` 4. 可以添一些事件来控制滚动的开始和停止,比如鼠标进入和离开暂停和恢复滚动效果: ```javascript listContainer.onmouseover = function(){ isScrolling = false; // 鼠标进入停止滚动 } listContainer.onmouseout = function(){ isScrolling = true; // 鼠标离开恢复滚动 } ``` 以上就是用原生JavaScript实现列表内容自动向上滚动效果的基本步骤。根据具体需求,还可以进行一些定制和调整,比如添缓动效果、点击按钮控制滚动等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值