sollrei / mini-note

https://github.com/GcFETeam/10min-quick-share/issues
3 stars 1 forks source link

IntersectionObserver #10

Open sollrei opened 5 years ago

sollrei commented 5 years ago

IntersectionObserver接口提供了目标元素(target)在根元素(root)中可视状态变化的监听方法。 可以用来更方便的实现类似图片懒加载,滚动加载更多,或者一些滚屏动画效果

123123 mov

先画一坨灰div
div*10{item}

    if ('IntersectionObserver' in window) {
      var observer = new IntersectionObserver(function (entries, _observer) {
        entries.forEach(item => {
          if (item.isIntersecting) { // 目标元素在根元素中可见(达到thresholds设置的范围)

            item.target.style.background = '#517791'; // 执行一些啥啥操作,这里只是改了背景色

            _observer.unobserve(item.target); // 取消观察
          }
        })
      }, {
        rootMargin: "0px 0px -60px 0px"  // 监听元素和root边界的偏移量,类似css margin。这里值是距离底部60像素

        // 这里还有两个可设置的属性:
        // root: 指定根元素,需要是目标元素的祖先元素,默认是浏览器视窗(viewport)
        // thresholds: 数组,值是监听元素和root边界交叉区域的比率
        //             例如设置[0.3, 0.7],意味在交叉区域面积30%和70%的位置会执行回调函数
        //             默认是0,即目标元素在root内一出现就会立即调用
      });

      document.querySelectorAll('div').forEach(item => { observer.observe(item) });
    }  

除了兼容性不太好没啥毛病

sollrei commented 5 years ago

https://developer.mozilla.org/zh-CN/docs/Web/API/Intersection_Observer_API