原生JS实现页面滚动条加载数据,页面下拉加载内容

一、前言

今天这个案例是滚动条事件,当滚动条距离底部的距离小于一个范围值时,会自动的增加页面的高度,从而达到永远划不到底部的效果。

二、scrollHeightscrollTopclientHeight的区别

document.documentElement.scrollHeight{\color{Red} } 网页的全文高

document.documentElement.scrollTop 滚动条距离顶部的距离(滚动条被卷去的距离)

document.documentElement.clientHeight 可以看到的屏幕高度

由于js没有给我们滚动条距离底部的距离我们就需要自己计算了 用网页的全文高减去滚动条距离顶部的距离减去可以看的的屏幕高度就可以得到滚动条距离底部的距离了。

三、代码

<style>
      body{
          padding-top: 2000px;
      }
  </style>
<body>
    <script>
        var body1 = document.getElementsByTagName("body")[0];
        var step = 500;
        var offsetx =0;
        console.log(body1);
        // body1.style.paddingBottom = 0;
        // body1.style.paddingBottom =offsetx;
        window.onscroll = function(){
            //网页全文高
           var pageHeight = document.documentElement.scrollHeight;
           //滚动条被卷去的距离
           var stop = document.documentElement.scrollTop; 
           //可以看到的屏幕高度
           var seeHeight = document.documentElement.clientHeight;
           //距离底部的距离
           var bottom1 = pageHeight - stop - seeHeight;
        //    console.log("距离底部的距离"+ bottom1)
        //    console.log("网页全文高"+pageHeight)
        //    console.log("滚动条被卷去的距离"+stop)
        //    console.log("可以看到的屏幕高度"+seeHeight)
        //    console.log("---------")
           //当滚动条距离距离底部小于200的时候就触发
           if(bottom1<=200){
                offsetx+=step;
                body1.style.paddingBottom = offsetx +"px";
                // alert("加载")
                // document.write('111111111111111111111111')
           }
        //console.log(e)
        }
    </script>

这个记录下来为了方便以后使用的方便,也希望大佬们多多交流,多多留言,指出我的不足的之处啦!

有需要的小伙伴可以研究研究啦!!

猜你喜欢

转载自blog.csdn.net/A20201130/article/details/122916202