前端滚动页面获取可见区域dom

/*
 * @Description: 监控dom是否在可视范围内
 * @Author: wangrui
 * @Date: 2021-08-05 13:59:58
 */
 IntersectionObserver不兼容safari浏览器,使用IntersectionObserver-polifill解决
export default class ViewPortLog {
  constructor(option) {
    // const {
    //   type 埋点方式
    //   targetClass,目标元素class类
    //   cb 回调函数
    // }=option;
    this.option = option;
    option && option.type==='domLog' && this.initDom();
  }

  // 获取浏览器视口高度
  initDom() {
    // 窗口可视高度
    this.viewPortHeight = window.innerHeight
      || document.documentElement.clientHeight
      || document.body.clientHeight;
  }

  // 方法一 IntersectionObserver 推荐使用
  getObserveDom() {
    const {
      targetClass
    } = this.option;
    const observer = new IntersectionObserver(isInObserve, { threshold: 1.0 });
    const item = document.getElementsByClassName(targetClass);
    for (let i = 0; i < item.length; i++) {
      observer.observe(item[i]);
    }

    function isInObserve(entries, observer) {
      entries.forEach((item) => { // 遍历entries数组
        if (item.isIntersecting) { // 当前元素可见
          // 派发事件在可视区域内
          this.option && this.option.cb(item.target)
          observer.unobserve(item.target)  // 停止观察当前元素 避免不可见时候再次调用callback函数
        }
      })
    }
  }

  // 方法二 DOM 需要绑定滚动事件 
  getViewportDom() {
    // 可视区域目标dom
    const {
      targetClass
    } = this.option;
    const item = document.getElementsByClassName(targetClass);

    const { scrollTop } = document.documentElement;
    for (let i = 0; i < item.length; i++) {
      const { offsetTop } = item[i];
      const top = offsetTop - scrollTop;
      if (top <= this.viewPortHeight) {

        // 派发事件在可视区域内
        this.option && this.option.cb(item, i)
      }
    }

  }

}   
//   domLog调用方式
//   new ViewPortLog({
//     targetClass:'log_item',
//     cb:(el,i)=>{}
//   }).getViewportDom()

//   IntersectionObserver调用方式
//   new ViewPortLog({
//     targetClass:'log_item',
//     cb:(el)=>{}
//   }).getObserveDom()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值