javascript实现上拉加载功能(适用pc/h5开发)

javascript实现上拉加载功能(适用pc/h5)

在开发经常碰到上拉加载的使用,但是使用三方库又容易使的文件太多太大,不利于性能,为了适应业务处理pc 和 h5页面开发 只能自己封装。话不多说,先上代码和测试结果。

上拉加载核心代码实现,个人放在toLowerDownLoad.js中

class ToLowerDownLoad {
  constructor({ ele = null, callBack, toLowerBottom = 50, delayTime = 100 }) {
    this.ele = ele ? document.querySelector(`#${ele}`) : window;
    this.callBack = callBack;
    this.toLowerBottom = toLowerBottom;
    this.delayTime = delayTime;
    this.toLowerBottomHandler();
    // 回调函数 callBack
    // 距离底部间距 toLowerBottom
    // delayTime 延迟回调时间
  }
  // 获取scrollTop
  getEleScrollTop(e) {
    if (this.isWindowType()) {
      // console.log(
      //   'window',
      //   e.target.documentElement.scrollTop || e.target.body.scrollTop
      // );
      return document.documentElement.scrollTop || document.body.scrollTop;
    }
    return e.target.scrollTop;
  }

  // 滚动条滚动高度
  getScrollHeight(e) {
    if (this.isWindowType()) {
      // console.log(
      //   'window11',
      //   e.target.documentElement.scrollHeight || e.target.body.scrollHeight
      // );
      return (
        document.documentElement.scrollHeight || document.body.scrollHeight
      );
    }
    return e.target.scrollHeight;
  }

  // 可视窗口高度
  getClientHeight(e) {
    if (this.isWindowType()) {
      // console.log(
      //   'window22',
      //   e.target.documentElement.clientHeight || e.target.body.clientHeight
      // );
      return (
        document.documentElement.clientHeight || document.body.clientHeight
      );
    }
    return e.target.clientHeight;
  }

  // 防抖 多次执行在一定时间内只触发一次
  toLowerDebounce(callback, duration) {
    const _this = this;
    return (function (...args) {
      let ctx = this;

      if (_this.timers) clearTimeout(_this.timers);

      _this.timers = setTimeout(() => {
        callback.apply(ctx, args);
      }, duration);
    })();
  }

  // 是否是window还是局部元素滚动
  isWindowType() {
    // console.log(Object.prototype.toString.call(_this.ele) === '[object HTMLDivElement]')
    // console.log(Object.prototype.toString.call(window) === '[object Window]')
    return Object.prototype.toString.call(this.ele) === '[object Window]';
  }

  toLowerBottomHandler() {
    const _this = this;
    // 监听scroll滚动

    this.ele.addEventListener('scroll', (e) => {
      // scrollHeight === clientHeight + scrollTop
      // 由此推出等式 scrollHeight - clientHeight - scrollTop
      const currentScroll = _this.getScrollHeight(e),
        currentClientHeight = _this.getClientHeight(e),
        currentScrollTop = _this.getEleScrollTop(e);

      const toLowerBottomSpace =
        Math.ceil(currentScroll) -
        Math.ceil(currentClientHeight) -
        Math.ceil(currentScrollTop);

      if (toLowerBottomSpace <= _this.toLowerBottom) {
        // 调用防抖
        _this.toLowerDebounce((...args) => {
          console.log(args);
          // 回调函数把实时滚动高度、当前窗口高度、滚动条的Scrolltop都返回
          _this.callBack({
            currentScroll,
            currentClientHeight,
            currentScrollTop,
          });
        }, _this.delayTime);
      }
    });
  }
}

// 使用es6 模块可以将注释去掉
// export default ToLowerDownLoad;


1.全局document滚动上拉触发加载
在这里插入图片描述

<div id="root"></div>
<script src="./toLowerDownLoad.js"></script>
<script>
  window.onload = function () {
    const getUiDom = document.getElementById('root');
    let count = 0;
    function inserHtml() {
      let strHtml = '';
      for (let i = 0; i < 40; i++) {
        count++;
        strHtml += `<li>页面滚动生成第${count}几个li</li>`;
      }

      getUiDom.insertAdjacentHTML('beforeEnd', strHtml);
    }

    inserHtml();

    new ToLowerDownLoad({
      callBack: (obj) => {
        console.log('触发了', obj);
        inserHtml();
      },
      toLowerBottom: 50,
      delayTime: 300,
    });
  };
</script>

2.测试2 某一个元素内部滚动上拉触发加载
在这里插入图片描述
测试2

<style>
  #root {
    height: 500px;
    background-color: aqua;
    overflow-y: auto;
  }
  .root-ul {
    height: 300px;
    background-color: rgb(255, 196, 218);
    width: 100%;
  }
</style>

<div id="root">
  <ul id="root-ul"></ul>
</div>

<script src="./toLowerDownLoad.js"></script>
<script>
  const getUiDom = document.getElementById('root-ul');
  let count = 0;
  function inserHtml() {
    let strHtml = '';
    for (let i = 0; i < 30; i++) {
      count++;
      strHtml += `<li>页面滚动生成第${count}几个li</li>`;
    }

    getUiDom.insertAdjacentHTML('beforeEnd', strHtml);
  }

  inserHtml();

  new ToLowerDownLoad({
    ele: 'root',
    callBack: (obj) => {
      console.log('触发了', obj);
      inserHtml();
    },

    toLowerBottom: 30,
    delayTime: 300,
  });
</script>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追逐梦想之路_随笔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值