原生javascript移动端滚动到底部加载更多数据效果代码

这里写图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{margin:0;padding:0;}
        #od{height:800px;}
        .box{height:100px;background:#ccc;margin:10px 0;}
    </style>
</head>
<body>
    <div class="ob" id="od">
		我是主体内容
    </div>
    <script>
        
        var timerId = null; //定时id

        window.onscroll = function(){
            var box =  document.createElement("div");
            var body = document.body;
            box.className = "box";

            var scrollTop = document.body.scrollTop;    //页面滚动高度
            var windheight = document.body.offsetHeight;    //页面总的宽度
            var h= document.documentElement.clientHeight || document.body.clientHeight;
            //视口宽度
            //滚动到底部
            if(scrollTop >= (windheight - h)){
                
                //发起请求,返回数据
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = function(){
                    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                        box.innerText = xmlhttp.responseText;
                    }
                }
                xmlhttp.open("GET", "json.json", true);
                xmlhttp.send(null);

                //设置延时避免滚动到底部时多次触发效果
                clearTimeout(timerId);
                timerId =  setTimeout(function(){
                    body.appendChild(box);
                },200);
            }
        }
    </script>
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值