上拉加载&&判断用户滑到底部

上拉加载在h5移动开发常常须要用到,就相似于 javascript

有兴趣的同窗能够查看react-loadmore,使用起来很是简单!java

通常咱们的作法是判断scrollTop和clientHeight对比scrollHeight,得出是否在底部。node

参考detect-if-browser-window-is-scrolled-to-bottomreact

let scrollTop =
      (document.documentElement && document.documentElement.scrollTop) ||
      document.body.scrollTop;
    let scrollHeight =
      (document.documentElement && document.documentElement.scrollHeight) ||
      document.body.scrollHeight;
    let clientHeight =
      document.documentElement.clientHeight || window.innerHeight;
    let scrolledToBottom =
      Math.ceil(scrollTop + clientHeight) >= scrollHeight;
复制代码

可是这种作法在移动端会有各类各样的问题,包括浏览器版本,ios,Android。ios

最近发现一种比较简单的办法~git

使用 Intersection Observer

此方法很是简单,只须要为元素生成一个IntersectionObserver,而且监听该元素,而后在监听的回调判断元素的intersectionRatio比率便可达到所需。这是核心代码.github

componentDidMount() {
    if (!this.props.Footer) this._svgaLoad();
    try {
      const node = document.getElementById('bottom')
      this.observer = new IntersectionObserver(this.insideViewportCb);
      this.observer.observe(node);
    } catch (err) {
      console.log("err in finding node", err);
    }
    window.addEventListener("scroll", this.handleOnScroll);
  }

  insideViewportCb(entries) {
    const { fetching, onBottom } = this.props;
    entries.forEach(element => {
      //在viewport里面
      if (element.intersectionRatio > 0&&!fetching) {
         onBottom();
      }
    });
  }
复制代码

给定一个底部的样式,而后用IntersectionObserver对它进行监听,只要判断它在viewportport就能够触发加载!浏览器

有兴趣的同窗能够查看react-loadmore,使用起来很是简单!bash

相关文章
相关标签/搜索