客官们先看下是不是你们想要的效果 (*^_^*)
效果:
实现代码:
HTML:
html
<div class="container">
<div class="block">
<img data-src="https://picsum.photos/200/200" alt="">
</div>
<div class="block">
<img data-src="https://picsum.photos/200/200" alt="">
</div>
<div class="block">
<img data-src="https://picsum.photos/200/200" alt="">
</div>
<div class="block">
<img data-src="https://picsum.photos/200/200" alt="">
</div>
<div class="block">
<img data-src="https://picsum.photos/200/200" alt="">
</div>
<div class="block">
<img data-src="https://picsum.photos/200/200" alt="">
</div>
<div class="block">
<img data-src="https://picsum.photos/200/200" alt="">
</div>
<div class="block">
<img data-src="https://picsum.photos/200/200" alt="">
</div>
<div class="block">
<img data-src="https://picsum.photos/200/200" alt="">
</div>
<div class="block">
<img data-src="https://picsum.photos/200/200" alt="">
</div>
</div>
CSS:
css
.block {
width: 200px;
height: 200px;
border: 1px solid #000;
box-sizing: border-box;
margin: 20px auto;
}
.block img {
width: 100%;
height: 100%;
}
JavaScript:
javascript
// 创建一个intersection observer实例
const observer = new IntersectionObserver(entries => {
entries.forEach((entry, index) => {
console.log(entry);
const img = entry.target;
// 放一张本地图片
img.src = './img/1.png';
if (entry.isIntersecting) {
console.log(index, '进入可视区域');
// 模拟加载慢情况
setTimeout(() => {
// 加载图片
img.src = img.dataset.src;
img.onload = () => {
console.log('图片加载完成');
observer.unobserve(img);
};
}, 1000);
}
// else {
// console.log(index, '离开可视区域');
// }
});
});
// 观察目标节点
const blockEls = document.querySelectorAll('.block img');
// 配置观察选项
const config = {
root: document.querySelector('.container'),
rootMargin: '0px',
threshold: 1
};
blockEls.forEach(blockEl => {
// 观察目标节点
observer.observe(blockEl, config);
});