首页 > 其他分享 >监听元素进入视口

监听元素进入视口

时间:2023-01-30 22:44:53浏览次数:52  
标签:preLoad vue 元素 视口 viewport lazyload 监听 rect

概述

突然想到,vue-lazyload不就是图片进入视口时才加载的吗,既然我要用vue-lazyload,那为什么不干脆研究一下vue-lazyload是如何判断元素进入视口的呢。

原理

通过参考资料1可知,vue-lazyload用于判断元素是否进入视口的代码如下:

checkInView () { 
  this.getRect() // 调用dom的getBoundingClientRect()
  return 
     this.rect.top < window.innerHeight * this.options.preLoad // preLoad默认是1.3
  && this.rect.bottom > this.options.preLoadTop // preLoadTop默认是0
  && this.rect.left < window.innerWidth * this.options.preLoad 
  && this.rect.right > 0
}

getBoundingClientRect()函数返回一个DOMRect,其包含 x,y,left,top,right,bottom这6个属性,如下所示:
img

三方插件

我自己不会去实现这样一个组件,因为到时候测起bug来令人奔溃。为什么不把这个工作交给别人,把节省下来的时间做其他事情呢。于是我找到了这样一些插件:

  • vue-in-viewport-directive:只能够实现在元素进入视口时显示的功能,并不能监听事件。
  • vue-mixin-in-viewport:基于Intersection Observer API的实现,如果要兼容老浏览器,要使用polyfill的版本。

REFS

  1. Vue-lazyload原理详解之源码解析
  2. vue-in-viewport-directive
  3. vue-mixin-in-viewport

标签:preLoad,vue,元素,视口,viewport,lazyload,监听,rect
From: https://www.cnblogs.com/hdxg/p/17077464.html

相关文章