Fork me on GitHub

判断元素是否在可视区域

如何判断元素是否出现在可视区?

方法一:

1.通过document.documentElement.clientHeight || window.innerHeight 获取屏幕可视窗口高度
2.通过element.offsetTop获取元素相对于文档顶部的距离
3.通过document.documentElement.scrollTop || document.body.scrollTop 获取浏览器窗口顶部与文档顶部之间的距离,也就是滚动条滚动的距离
如果2 - 3 < 1成立,则元素在可视区域

1
2
3
4
5
function isInSight1(el) {
const innerHeight = document.documentElement.clientHeight || window.innerHeight;
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
return el.offsetTop - scrollTop < innerHeight;
}

方法二:getBoundingClientRect()

这个方法返回一个名为ClientRect的DOMRect对象,包含了top、right、botton、left、width、height这些值。

1
2
3
4
5
function isInSight2(el) {
const bound = el.getBoundingClientRect();
const innerHeight = document.documentElement.clientHeight || window.innerHeight;
return bound.top <= innerHeight + 100;
}

方法三:IntersectionObserver

这个API可以自动观察元素是否在视口内。
参考资料:
API Sketch for Intersection Observers

基本使用:

1
2
3
4
5
6
7
var io = new IntersectionObserver(callback, option);
// 开始观察
io.observe(document.getElementById('example'));
// 停止观察
io.unobserve(element);
// 关闭观察器
io.disconnect();

callback的参数是一个数组,每个数组都是一个IntersectionObserverEntry对象,包括以下属性:

属性 描述
time 可见性发生变化的时间,单位为毫秒
rootBounds 同getBoundingClientRect方法返回值相同
boundingClientRect 目标元素的矩形区域信息
intersectionRect 目标元素与视(或根元素)的交叉区域信息
intersectionRatio 目标元素的可见比例,即intersectionRect占boundingClientRect的比例,完全可见时为1,完全不可见时小于等于0
target 被观察的目标元素

我们需要用到intersectionRatio来判断是否在可视区域内,当intersectionRatio > 0 && intersectionRatio <= 1即在可视区域内。

应用:实现图片懒加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 替换img标签的src,加载图片资源
function loadImg(el) {
const source = el.dataset.src;
el.src = source;
}

const io = new IntersectionObserver(ioes => {
ioes.forEach(ioe => {
// 被观察的目标元素,是一个 DOM 节点对象
const el = ioe.target;
const intersectionRatio = ioe.intersectionRatio;
// intersectionRatio:完全可见时为1,完全不可见时小于等于0
if (intersectionRatio > 0 && intersectionRatio <= 1) {
if (!el.src) {
loadImg(el);
}
}
el.onload = el.onerror = () => io.unobserve(el);
});
});

const imgs = document.querySelectorAll('.pic'); // 获取需要懒加载的全部图片元素
imgs.forEach(item => io.observe(item));

本文标题:判断元素是否在可视区域

文章作者:tongtong

发布时间:2019年03月14日 - 17:03

最后更新:2019年03月15日 - 16:03

原始链接:https://ilove-coding.github.io/2019/03/14/判断元素是否在可视区域/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!
-------------本文结束-------------