元素是否可见
wǎng luò shí huāng 2022-01-11
学习es5
判断元素是否可见的 2 种方案
参考阮一峰的日志:
- IntersectionObserver API 使用教程
- 里面还提到了传统的getBoundingClientRect()方法。
- 浏览器的五种观察者模式:
- https://zhuanlan.zhihu.com/p/482144072
- https://mp.weixin.qq.com/s/ymlfp_5nhbJpUuYvYpRI2w
- IntersectionObserver 的使用
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.getAttribute("src");
img.classList.remove("lazy-load");
observer.unobserve(img);
}
});
});
document.querySelectorAll(".lazy-load").forEach((img) => {
observer.observe(img);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14