实现方式

  • getBoundingClientRect
  • offsetTop、scrollTop
  • IntersectionObserver

getBoundingClientRect

适用于元素相对于整个窗口的检测

offsetTop、scrollTop

适用于元素相对于元素的检测

IntersectionObserver

适用于元素相对于元素的检测

private playControl() {
    // entries为触发观察设定条件的观察者实例集合,observer为主体
    const callback = (entries: IntersectionObserverEntry[], observer: IntersectionObserver) => {
      for (const entry of entries) {
        const {
          boundingClientRect,
          intersectionRatio,
          intersectionRect,
          isIntersecting,
          rootBounds,
          target,
          time
        } = entry
        // 当被观察元素在可视范围内的时候,isIntersecting为true,否则为false
        if (isIntersecting) {
          this.$emit('visible', true)
        } else {
          this.$emit('visible', false)
        }
      }
    }
    const observer = new IntersectionObserver(callback, {
      threshold: 0.1, // 检测范围,0.0~1.0之间,为0.0时表示观察对象和主体之间存在1px的交叉时,都会将观察对象标定为在可视范围内;为1.0时,要求观察对象完全暴露在主体内,才会将观察对象标定为在可视范围内。
      root: this.$el.parentElement // 主体,观察对象应该为主体内的元素
    })
    observer.observe(this.$el)
  }

参考资料

JavaScript如何判断一个元素是否在可视区域中?