适用范围
优点
- 可以设定预加载,把判断的区域设置的比可视区域大一点
缺点
- 需要监听滚动等事件,重复查询,会对性能产生一定的影响
获取目标元素与可视区域的相对偏移
- 使用 getBoundingClientRect方法返回元素的大小及其相对于视口的位置,可以得到当前元素相对
可视区域
的坐标:
const { top, left, bottom, right } = el.getBoundingClientRect();
- 分别是与可视区域的上、下、左右边框偏移量
获取可视区域的宽高
得到元素的坐标信息后,就需要获得 可视区域
的宽高来帮助我们确定是否在范围内:
const { innerHeight, innerWidth } = window;
- child::innerHeight与innerWidth
判断元素是否在可视区域中
判断元素头部或者底部是否在 可视区域
出现:
(top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)
判断元素左部或者右部是否在 可视区域
出现:
(left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)
当需要整个元素都出现在屏幕的时候,需要同时判断四个相对坐标:
top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth