<!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>
</head>
<style>
.box {
width: 500px;
height: 500px;
overflow-y: auto;
}
.mb20{
width: 50px;
height: 200px;
}
</style>
<body>
<div class="box">
<img class="mb20" src="" data-src="./img.png" alt="">
<hr>
<img class="mb20" src="" data-src="./dsj3.png" alt="">
<hr>
<img class="mb20" src="" data-src="./hd51.png" alt="">
<hr>
<img class="mb20" src="" data-src="./shop3.png" alt="">
</div>
<script>
const imgList = [...document.querySelectorAll('img')]
var io = new IntersectionObserver((entries) => {
entries.forEach(item => {
if (item.isIntersecting) {
item.target.src =item.target.dataset.src
io.unobserve(item.target)
}
})
}, {
root: document.querySelector('.box')
})
// observe遍历监听所有img节点
imgList.forEach(img => io.observe(img))
</script>
</body>
</html>
图片懒加载IntersectionObserver 得observe方法
最新推荐文章于 2024-05-19 11:27:40 发布