1、页面一加载就只显示四张图片
2、随着滚轮向下滑动,实现图片一张一张加载出来
3、通过一段代码来实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.viewport {
width: 250px;
height: 200px;
border: 1px solid blue;
overflow: auto;
}
.box1 {
height: 600px;
width: 100%;
}
.observed {
width: 100px;
height: 100px;
border: 1px solid green;
}
.imgs {
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="viewport" id="viewport">
<div class="box1">
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
<img src="./place.jpg" data-src="https://img.yzcdn.cn/vant/cat.jpeg" alt="图片" class="imgs" />
</div>
</div>
<script>
let viewport = document.getElementById("viewport"); // 可视区域
let imgList = document.querySelectorAll(".imgs"); // 被观察元素
let fn = (e)=>{
// console.log(e,2222);
e.forEach(item=>{
// console.log(item.isIntersecting,666);
// item.isIntersecting可以看出在视口范围里为true,不在为false
if(item.isIntersecting){
// item.target.src 获取图片src
// getAttribute('data-src') 获取自定义属性data-src
// 在视口里面就赋值
item.target.src = item.target.getAttribute('data-src')
}
})
}
// 开启监听
let IO = new IntersectionObserver(fn,{})
console.log(IO);
// 遍历拿到每张图片并监听视口中的图片
imgList.forEach(item=>{
IO.observe(item)
})
</script>
</body>
</html>